The numpy module provides a function numpy.ndarray.tolist(), used to convert the data elements of an array into a list. This function returns the array as an a.ndim- levels deep nested list of Python scalars.
In simple words, this function returns a copy of the array elements as a Python list. The elements are converted to the nearest compatible built-in Python type through the item function. When 'a.ndim' is 0, then the depth of the list is 0, and it will be a simple Python scalar, not any list.
ndarray.tolist()
This function has no arguments or parameters.
This function returns the possibly nested list of array elements.
If we will use a.tolist() for a 1D array then it will be almost the same as list(a), except that tolist converts numpy scalars to Python scalars.
import numpy as np a = np.uint32([6, 2]) a a_list=list(a) a_list type(a_list[0]) a_tolist=a.tolist() a_tolist type(a_tolist[0])
Output:
In the above code
In the output, it shows a list and the type whose elements are transformed from the source array.
For a 2-dimensional array, tolist is applied recursively.
import numpy as np a = np.array([[11, 21], [31, 41]]) b=a.tolist() a b
Output:
In the above code
In the output, it shows a list whose elements are transformed from the source array.
import numpy as np x = np.array(5) list(x) y=x.tolist() y
Output: