Join the Stack Overflow Community
Stack Overflow is a community of 6.5 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

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

share|improve this question
up vote 177 down vote accepted

Use tolist():

import numpy as np
>>> np.array([[1,2,3],[4,5,6]]).tolist()
[[1, 2, 3], [4, 5, 6]]
share|improve this answer

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]]
share|improve this answer

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`
share|improve this answer

You can also use the list keyword of Python to create a list from the numpy array:

import numpy as np
nda = np.arange(10).reshape(2,5)
ndlist = list(nda)
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.