Convert NumPy array to Python list

Question:

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

Asked By: Alex Brooks

||

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

Answered By: Peter Hansen

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`
Answered By: CodingMatters

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))
Answered By: Shivid
c = np.array([[1,2,3],[4,5,6]])

list(c.flatten())
Answered By: Harshal SG

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.

Answered By: rahul-ahuja

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)
Answered By: Charchit Shukla
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.