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.
1 Answer
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))
5 Comments
iGian
my_list = arrays[:] :) Not iterative though!Sheldore
@iGian: True that. I thought OP wants iterative solution, one at a time. What you wrote is basically cloning a list
MysteryGuy
Thank you ! Actually, I was doing stuff with np.append and it was concatenating all things, losing the array structure. Is it possible to work np.append too to solve my problem ?
Sheldore
@MysteryGuy: Wait for the numpy solution. I will update in a minute
Sheldore
@MysteryGuy: I added the numpy solution.
my_list? Doesn't that do what you need?