413

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

Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
Alex Brooks
  • 5,133
  • 4
  • 21
  • 27

6 Answers6

572

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

Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
Peter Hansen
  • 21,046
  • 5
  • 50
  • 72
  • 9
    If your list is float32 `tolist` will convert it to `floats`s - that's not desired probably. Using `list(myarray)` doesn't suffer from this - why should we prefer `tolist` ? – Mr_and_Mrs_D Jul 03 '17 at 20:46
  • 1
    @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.) – Peter Hansen Jul 04 '17 at 00:41
  • 2
    I never mentioned integers - try `float32_array = np.array([0.51764709], np.float32); print(float32_array.tolist()); print(list(float32_array))` – Mr_and_Mrs_D Jul 04 '17 at 07:54
  • 3
    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. – Peter Hansen Jul 04 '17 at 15:21
  • Along those lines: `np.array([[0, 'one'], ['two', 3]]).tolist() -> [['0', 'one'], ['two', '3']]` – keithpjolley Mar 20 '19 at 19:58
  • @Mr_and_Mrs_D To answer above question, we should prefer `tolist` when we want to serialize the data to json or yaml file. – off99555 Aug 08 '22 at 15:57
18
c = np.array([[1,2,3],[4,5,6]])

list(c.flatten())
Jeru Luke
  • 20,118
  • 13
  • 80
  • 87
Harshal SG
  • 403
  • 3
  • 7
16

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`
BUFU
  • 127
  • 11
CodingMatters
  • 1,275
  • 16
  • 26
  • 9
    to get a flat list, there is also `a.flatten().tolist()` (or `list(a.flatten())` cf discussion above) – ClementWalter Oct 26 '20 at 15:52
  • @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? – deps_stats Nov 02 '21 at 00:54
  • 1
    @deps_stats this is because `np.array(arr.tolist()) == arr`; in other words `.tolist` is sort of a serialization of `arr` – ClementWalter Nov 03 '21 at 07:39
7

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))
Shivid
  • 1,295
  • 1
  • 22
  • 36
3

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.

rahul-ahuja
  • 1,166
  • 1
  • 12
  • 24
-1

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)