Numpy ndarray tolist() function converts the array to a list. If the array is multi-dimensional, a nested list is returned.
Numpy array to list
To convert np array to list in Python, use the np.tolist() function. The Numpy tolist() function converts the values from whatever numpy type they may have (for example, np.int32 or np.float32) to the “nearest compatible Python type”. The tolist() method returns the array as an a.ndim-levels deep nested list of Python scalars.
If a.ndim is 0, then since the depth of the nested list is 0, it will not be a list at all but a simple Python scalar.
See the following code.
import numpy as np arr = np.array([11, 21, 19]) print(f'NumPy Array: {arr}') print(type(arr)) list1 = arr.tolist() print(f'List: {list1}') print(type(list1))
Output
NumPy Array: [11 21 19] <class 'numpy.ndarray'> List: [11, 21, 19] <class 'list'>
In the above example, we have defined the array using the np.array() function and then print its data type.
Then we have used print the array type of array using type() function.
In the next step, we have used tolist() function to convert the numpy array to a list and print the list and its data type.
If you want to preserve the numpy data types, you could call list() on your array instead, and you’ll end up with the list of numpy scalars.
See the following code.
import numpy as np arr = np.array([11.19, 21.22, 19.59]) print(f'NumPy Array: {arr}') print(type(arr)) list1 = list(arr) print(f'List: {list1}') print(type(list1))
Output
NumPy Array: [11.19 21.22 19.59] <class 'numpy.ndarray'> List: [11.19, 21.22, 19.59] <class 'list'>
In the above example, we have defined the array with floating values and then use the Python list() function to convert the array to a list.
Convert two-dimensional array to list
To convert a two-dimensional array to a list in numpy, use the ndarray.tolist() method.
import numpy as np arr = np.array([[11.19, 21.22], [19.59, 46.21]]) print(f'NumPy Array: {arr}') print(type(arr)) list1 = arr.tolist() print(f'List: {list1}') print(type(list1))
Output
NumPy Array: [[11.19 21.22] [19.59 46.21]] <class 'numpy.ndarray'> List: [[11.19, 21.22], [19.59, 46.21]] <class 'list'>
In this example, the tolist() function is applied recursively.
Convert multi-dimensional array to list
To convert a multi-dimensional array to list in numpy, use the np.tolist() method. First, let’s convert the multi-dimensional array into a list and see the output.
import numpy as np arr = np.array([[11.19, 21.22], [19.59, 46.21], [21.19, 18.21]]) print(f'NumPy Array: {arr}') print(type(arr)) list1 = arr.tolist() print(f'List: {list1}') print(type(list1))
Output
NumPy Array: [[11.19 21.22] [19.59 46.21] [21.19 18.21]] <class 'numpy.ndarray'> List: [[11.19, 21.22], [19.59, 46.21], [21.19, 18.21]] <class 'list'>
The numpy tolist() function produces nested lists if the numpy array shape is 2D or multi-dimensional.
That is it for this tutorial.