How to fill iteratively a list with arrays in Python?

Question:

I have an empty list my_list=[] and I want to iteratively add arrays to this list. Suppose my arrays are [1,2,3], [4,5,6], [7,8,9],[10,11,12], I want to have a list such that my_list=[[1,2,3], [4,5,6], [7,8,9], [10,11,12]] such that each element of the list is an array.

Asked By: MysteryGuy

||

Answers:

Just use append. Sample example assuming you have four variables storing the arrays/lists to add to the list

my_list=[] 
a = [1,2,3]
b = [4,5,6]
c = [7,8,9]
d = [10,11,12]

my_list.append(a)
my_list.append(b)
my_list.append(c)
my_list.append(d)

# [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]

If you want some iterative solution, use the following list comprehension way. Although here finally my_list and arrays are the same.

arrays = [[1,2,3], [4,5,6], [7,8,9], [10,11,12]]

my_list = [i for i in arrays]

If you don’t prefer list comprehension

my_list = []
for i in arrays:
    my_list.append(i)

NumPy way : One of the possible solutions using append

arrays = np.array([[1,2,3], [4,5,6], [7,8,9], [10,11,12]])
my_list = np.empty((0,len(arrays[0])))

for arr in arrays:
    my_list = np.append(my_list, [arr], axis=0)

Another way using vstack where 3 in (0,3) correspond to the number of columns (length of a single list).

my_list = np.array([]).reshape(0,3)

for arr in arrays:
    my_list = np.vstack((my_list, arr))
Answered By: Sheldore
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.