Home » Python » Converting NumPy array into Python List structure?

# Converting NumPy array into Python List structure?

Questions:

How do I convert a NumPy array to a Python List (for example `[[1,2,3],[4,5,6]]` ), and do it reasonably fast?

``````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.)

Questions:

NumPy arrays have a tolist method:

``````In [1]: arr=np.array([[1,2,3],[4,5,6]])

In [2]: arr.tolist()
Out[2]: [[1, 2, 3], [4, 5, 6]]
``````

Questions:

The numpy .tolist method produces nested arrays 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`
``````

Questions:

If you have a ndarray in numpy called narray

Example

``````narray[0] = [[[ 87 137]] [[ 87 138]] [[ 86 139]][[ 85 140]][[ 85 141]]]
narray[1] = [[[ 84 142]] [[ 84 143]] [[ 83 144]]]
narray[2] = [[[ 82 145]] [[ 81 146]] [[ 80 147]] [[ 79 148]] [[ 78 149]] [[ 77 150]][[ 77 151]]]
``````

You could just loop inside a loop like to extra each element separately

``````for i in range(len(narray)):
i_narray = narray[i]
for j in range(len(i_narray)):
print(i_narray[j],"\n")
``````

This is the output

``````[[ 87 137]]

[[ 87 138]]

[[ 86 139]]

[[ 85 140]]

[[ 85 141]]

[[ 84 142]]

[[ 84 143]]

[[ 83 144]]

[[ 82 145]]

[[ 81 146]]

[[ 80 147]]

[[ 79 148]]

[[ 78 149]]

[[ 77 150]]

[[ 77 151]]
``````

Hope it helps someone 🙂