Python appending array to an array

Question:

I am currently working on DES implementation.In one part of the code I have to append array to an array.Below is my code:

C0=[1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1]

def Fiestel():
    C=[]
    C.append(C0)
    temp=[0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1]
    C.append(temp)
    print(C)
Fiestel()

How do I append an array to an existing array.I even tried declaring C as 2d array.Thankx in advance for helping.

Each element is an array itself.

enter image description here

Asked By: shubhamj

||

Answers:

You can append the elements of one list to another with the "+=" operator. Note that the "+" operator creates a new list.

a = [1, 2, 3]
b = [10, 20]

a = a + b # Create a new list a+b and assign back to a.
print a
# [1, 2, 3, 10, 20]


# Equivalently:
a = [1, 2, 3]
b = [10, 20]

a += b
print a
# [1, 2, 3, 10, 20]

If you want to append the lists and keep them as lists, then try:

result = []
result.append(a)
result.append(b)
print result
# [[1, 2, 3], [10, 20]]
C0=[1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1]

def Fiestel():
    C=C.append(C0)
    temp=[0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1]
    C0=C0.append(temp)
    return C

C0=Fiestel()
print (C0)

Try this, I think this is what you are looking for.

Answered By: Issac Saji

Apart from + operator there’s another way to do the same i.e. extend()

a = [1, 2, 3]
b = [10, 20]

a.append(b) # Output: [1, 2, 3, [10, 20]]
a.extend(b) # Output: [1, 2, 3, 10, 20]

You can use these 2 functions for manipulating a list as per your requirement.

Answered By: Manasvi Batra

One way is to unpack both the lists:

a = [1, 2, 3]
b = [10, 20]

[*a,*b] 

#output 
[1, 2, 3, 10, 20]

if you want to use numpy then:

import numpy as np
a=np.array(a)
b=np.array(b)
list(np.append(a,b))

#output
[1, 2, 3, 10, 20]
Answered By: God Is One
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.