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 vote

Best answer

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

- Using
*concatenate()* - Using
*hstack()* - Using
*stack()* - Using vstack()
- 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]