444

How do I convert a NumPy array into a Python List?

0

7 Answers 7

619

Use tolist():

>>> import numpy as np
>>> np.array([[1,2,3],[4,5,6]]).tolist()
[[1, 2, 3], [4, 5, 6]]

Note that this converts the values from whatever numpy type they may have (e.g. np.int32 or np.float32) to the "nearest compatible Python type" (in a list). If you want to preserve the numpy data types, you could call list() on your array instead, and you'll end up with a list of numpy scalars. (Thanks to Mr_and_Mrs_D for pointing that out in a comment.)

Sign up to request clarification or add additional context in comments.

6 Comments

If your list is float32 tolist will convert it to floatss - that's not desired probably. Using list(myarray) doesn't suffer from this - why should we prefer tolist ?
@Mr_and_Mrs_D are you suggesting that, despite having floats in your array, you'd like to have the resulting list be integers? That's sort of a whole different question... and of course you'd have to specify that despite being float32 values, they're all going to be integral. Anyway, if you had that situation, I guess doing myarray.astype(np.int32).tolist() would be an option, and explicit about what you're trying to accomplish. (And lastly, list(array_of_type_float32) doesn't give integers here when I tried it... so I don't know what you're asking.)
I never mentioned integers - try float32_array = np.array([0.51764709], np.float32); print(float32_array.tolist()); print(list(float32_array))
Okay, so the one converts to [float] and the other uses the numpy scalar float32 type still, as [np.float32]. Fine. Good to know, but I guess whether it's desirable or not depends on each specific case. For what it's worth, I suspect that generally when someone (like the OP) asks for conversion to a list, they implicitly mean a list of regular Python data types, in this case either floats or integers, and not a list of numpy scalar types. Thanks for pointing this out: I've edited the answer to include a note about that.
Along those lines: np.array([[0, 'one'], ['two', 3]]).tolist() -> [['0', 'one'], ['two', '3']]
|
25
c = np.array([[1,2,3],[4,5,6]])

list(c.flatten())

Comments

17

The numpy .tolist method produces nested lists if the numpy array shape is 2D.

if flat lists are desired, the method below works.

import numpy as np
from itertools import chain

a = [1,2,3,4,5,6,7,8,9]
print type(a), len(a), a
npa = np.asarray(a)
print type(npa), npa.shape, "\n", npa
npa = npa.reshape((3, 3))
print type(npa), npa.shape, "\n", npa
a = list(chain.from_iterable(npa))
print type(a), len(a), a`

3 Comments

to get a flat list, there is also a.flatten().tolist() (or list(a.flatten()) cf discussion above)
@ClementWalter Thanks! That comment is worth much more than the answer itself. Do you happen to know why .tolist() creates a nested list? Why do we have to go through so many steps to get a simple list? What's the rationale?
@deps_stats this is because np.array(arr.tolist()) == arr; in other words .tolist is sort of a serialization of arr
9

tolist() works fine even if encountered a nested array, say a pandas DataFrame;

my_list = [0,1,2,3,4,5,4,3,2,1,0]
my_dt = pd.DataFrame(my_list)
new_list = [i[0] for i in my_dt.values.tolist()]

print(type(my_list),type(my_dt),type(new_list))

Comments

4

Another option

c = np.array([[1,2,3],[4,5,6]])

c.ravel()
#>> array([1, 2, 3, 4, 5, 6])

# or
c.ravel().tolist()
#>> [1, 2, 3, 4, 5, 6]

also works.

Comments

0

The easiest way to convert array to a list is using the numpy package:

import numpy as np
#2d array to list
2d_array = np.array([[1,2,3],[8,9,10]])
2d_list = 2d_array.tolist()

To check the data type, you can use the following:

type(object)

Comments

0

It might be to simple but it was not mentioned yet:

In case you do not need an "indepth" conversion you can simply cast via list():

>>> import numpy as np  
>>> a=np.array(\[\[1,2,3\],\[4,5,6\]\])
>>> list(a)
[array(\[1, 2, 3\]), array(\[4, 5, 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.