How to convert np array to list?
With NumPy, np.array objects can be converted to a list with the tolist() function. The tolist() function doesn’t accept any arguments. If the array is one-dimensional, a list with the array elements is returned. For a multi-dimensional array, a nested list is returned.
In order to complete this tutorial, you will need:
This tutorial was tested with Python 3.9.6 and NumPy 1.23.3.
Let’s construct a one-dimensional array of [1, 2, 3]:
This code will output:
Now, let’s use tolist():
This new code will output:
The array has been converted from numpy scalars to Python scalars.
Let’s construct a multi-dimensional array of [ [1, 2, 3], [4, 5, 6] ]:
This code will output:
Now, let’s use tolist():
This new code will output:
The array has been converted from numpy scalars to Python scalars.