0

Say I have 3 numpy arrays: array([1, 2]), array([1, 2, 3]) and array([1, 2, 3, 4])

I want to get a list that look like [array([1, 2]), array([1, 2, 3]), array([1, 2, 3, 4])]

This can be done directly. However, I wonder how to get it done iteratively. Because if I start with L=[] and do

for i in range(3,6):
    L=[L, np.array(range(1,i))]

Then finally I will get a list of lists: [[[[], array([1, 2])], array([1, 2, 3])], array([1, 2, 3, 4])]. How can I get the desired result? Thanks.

The np.array(range(1,i)) is just an example. It can be any 1-D numpy array.

2 Answers 2

1
L = []
for i in range(3,6):
    L.append(np.array(range(1,i)))

The creates:

[array([1, 2]), array([1, 2, 3]), array([1, 2, 3, 4])]

Alternatively, because L is a python list and not a numpy array:

L = []
for i in range(3,6):
    L = L + [np.array(range(1,i))]
Sign up to request clarification or add additional context in comments.

Comments

0

What you are doing will work if you use append or +=, but you can also do this easily with the list comprehension:

[np.arange(1, i) for i in range(3,6)]

Comments

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.