NumPy Tutorial NumPy Statistics NumPy References

NumPy - ndarray.tolist() function



The NumPy ndarray.tolist() function returns a copy of the array data as a (nested) Python list. Data items are converted to the nearest compatible built-in Python type.

If the dimension of the array 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.

Syntax

numpy.ndarray.tolist()

Parameters

No parameter is required.

Return Value

Returns the possibly nested Python list containing array elements.

Example:

In the example below, numpy arrays are converted into Python lists.

import numpy as np

#0-D numpy array
Arr0 = np.array(100)
#1-D numpy array
Arr1 = np.arange(1, 6)
#2-D numpy array
Arr2 = np.arange(1, 7).reshape(2,3)

#converting into python list
List0 = Arr0.tolist()
List1 = Arr1.tolist()
List2 = Arr2.tolist()

#displaying the result
print(List0)
print(List1)
print(List2)

The output of the above code will be:

100
[1, 2, 3, 4, 5]
[[1, 2, 3], [4, 5, 6]]

Example:

Data items are converted to the nearest compatible built-in Python type. Consider the example below:

import numpy as np

#1-D numpy array
Arr = np.arange(1, 6)

#converting into python list
MyList = Arr.tolist()

#displaying numpy array info
print(Arr)
print(type(Arr))
print(type(Arr[0]))

print()
#displaying python list info
print(MyList)
print(type(MyList))
print(type(MyList[0]))

The output of the above code will be:

[1 2 3 4 5]
<class 'numpy.ndarray'>
<class 'numpy.int64'>

[1, 2, 3, 4, 5]
<class 'list'>
<class 'int'>

❮ NumPy - Functions

5