+3 votes
in Programming Languages by (14.7k points)

I want to convert a list of NumPy arrays into a list. What function should I use to do this?

E.g.

From

[np.array([1,2,3]), np.array([4,5,6]), np.array([7,8,9])]

To

[1, 2, 3, 4, 5, 6, 7, 8, 9]

1 Answer

0 votes
by (25.6k points)
edited by

You can try one of the following methods to convert a list of NumPy arrays into a Python list.

  1. Using concatenate()
  2. Using hstack()
  3. Using stack()
  4. Using vstack()
  5. Converting the list of NumPy arrays into a NumPy array and then applying flatten() to the NumPy array

Here is an example to show these methods:

>>> import numpy as np
>>> a=[np.array([1,2,3]), np.array([4,5,6]), np.array([7,8,9])]
>>> a
[array([1, 2, 3]), array([4, 5, 6]), array([7, 8, 9])]
>>> list(np.hstack(a))
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(np.stack(a).flatten())
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(np.concatenate(a, axis=0))
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(np.vstack(a).flatten())
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(np.array(a).flatten())
[1, 2, 3, 4, 5, 6, 7, 8, 9]
 

...