0

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.

3
  • 1
    Can't you just add the lists to my_list? Doesn't that do what you need? Commented Jan 10, 2019 at 17:45
  • How do you get the arrays? from user input? Commented Jan 10, 2019 at 17:46
  • Also; list and array are same in python Commented Jan 10, 2019 at 18:09

1 Answer 1

2

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))
Sign up to request clarification or add additional context in comments.

5 Comments

my_list = arrays[:] :) Not iterative though!
@iGian: True that. I thought OP wants iterative solution, one at a time. What you wrote is basically cloning a list
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 ?
@MysteryGuy: Wait for the numpy solution. I will update in a minute
@MysteryGuy: I added the numpy solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.