The tolist()
method converts a NumPy array to a Python list without changing its data or dimensions.
import numpy as np
array1 = np.array([[0, 1], [2, 3]])
# convert a NumPy array to Python list
list1 = array1.tolist()
print(list1, type(list1))
# Output : [[0, 1], [2, 3]] <class 'list'>
Here, the elements and dimensions of list1 are the same as those of array1.
Note: For a single-dimensional array, array1.tolist()
is the same as list(array1)
.
tolist() Syntax
The syntax of tolist()
is:
ndarray.tolist()
tolist() Arguments
The tolist()
method takes no arguments.
tolist() Return Value
The tolist()
method returns a Python list.
Example 1: Convert a Multidimensional Array
The tolist()
method converts a multidimensional array into a nested list.
import numpy as np
array1 = np.array([[[0, 1], [2, 3]], [[4, 5], [6, 7]]])
# convert the array to list
list1 = array1.tolist()
print(list1)
Output
[[[0, 1], [2, 3]], [[4, 5], [6, 7]]]
Difference Between tolist() and list()
The key differences between tolist()
and list()
are
- The
tolist()
method converts a multidimensional array into a nested list whereaslist()
converts it to a list of arrays. For example,
import numpy as np
# create a 2-D array
array1 = np.array([[1, 2], [3, 4]])
# convert a 2-D array to nested list
list1 = array1.tolist()
# convert a 2-D array to a list of arrays
list2 = list(array1)
print('Using array.tolist(): ', list1)
print('Using list(array): ', list2)
Output
Using array.tolist(): [[1, 2], [3, 4]] Using list(array): [array([1, 2]), array([3, 4])]
tolist()
changes NumPy data types to Python data types, butlist()
doesn't.
import numpy as np
# create a numpy array
array1 = np.array([1, 2])
# convert an array to a list using tolist()
list1 = array1.tolist()
# convert an array to a list using list()
list2 = list(array1)
print("Datatype of original array:", type(array1[0]))
print("Datatype after using array.tolist():", type(list1[0]))
print("Datatype after using array.tolist():", type(list2[0]))
Output
Datatype of original array: <class 'numpy.int64'> Datatype after using array.tolist(): <class 'int'> Datatype after using array.tolist(): <class 'numpy.int64'>
tolist()
works with 0d numpy arrays, butlist()
doesn't.
import numpy as np
# create a list of arrays
array1 = np.array(123)
# convert an array to a list using tolist()
list1 = array1.tolist()
print(list1) #123
# convert an array to a list using list()
list2 = list(array1) #TypeError: iteration over a 0-d array
print(list2)
Output
123 TypeError: iteration over a 0-d array