How do I convert a NumPy array into a Python List?
Advertisement
Answer
Use tolist()
:
JavaScript
x
4
1
>>> import numpy as np
2
>>> np.array([[1,2,3],[4,5,6]]).tolist()
3
[[1, 2, 3], [4, 5, 6]]
4
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.)