0

Suppose I have 2D array, for simplicity, a=np.array([[1,2],[3,4]]). I want to convert it to list of arrays, so that the result would be:

b=[np.array([1,2]), np.array([3,4])]

I found out that there is np.ndarray.tolist() function, but it converts N-D array into nested list. I could have done in a for loop (using append method), but it is not efficient/elegant.

In my real example I am working with 2D arrays of approximately 10000 x 50 elements and I want list that contains 50 one dimensional arrays, each of the shape (10000,).

asked Aug 20, 2018 at 14:14
1
  • To iterate on the 2nd dimension, you may want to transpose the array first. Commented Aug 20, 2018 at 15:38

2 Answers 2

5

How about using list:

a=np.array([[1,2],[3,4]])
b = list(a)
answered Aug 20, 2018 at 14:18

1 Comment

Wow. This is the shortest possible solution I guess :)
3

Why don't you use list comprehension as follows without using any append:

a=np.array([[1,2],[3,4]])
b = [i for i in a]
print (b)

Output

[array([1, 2]), array([3, 4])]
answered Aug 20, 2018 at 14:17

6 Comments

[i for i in a] is a verbose way of sayin list(a)
Hmm you are right. But I guess in terms of timings, they shouldn't be different. Under the hood runs the same things IMO
about the same, but no they do not. list will be faster.
That's the beauty of SO. You get to know different and more efficient approaches. Thanks for the comment :)
check out this question for some gory details
|

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.