How do I convert a NumPy array into a Python List?
7 Answers
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.)
6 Comments
Mr_and_Mrs_D
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 ?Peter Hansen
@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.)Mr_and_Mrs_D
I never mentioned integers - try
float32_array = np.array([0.51764709], np.float32); print(float32_array.tolist()); print(list(float32_array))Peter Hansen
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.
keithpjolley
Along those lines:
np.array([[0, 'one'], ['two', 3]]).tolist() -> [['0', 'one'], ['two', '3']] |
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
ClementWalter
to get a flat list, there is also
a.flatten().tolist() (or list(a.flatten()) cf discussion above)deps_stats
@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?
ClementWalter
@deps_stats this is because
np.array(arr.tolist()) == arr; in other words .tolist is sort of a serialization of arr