NumPy ndarray.tolist()
The numpy.ndarray.tolist()
method converts a NumPy array into a nested list.
This method returns a standard Python list representation of the array, making it useful for interoperability with Python data structures.
Syntax
ndarray.tolist()
Return Value
Returns a nested Python list representation of the array. The structure of the list matches the shape of the original array.
Examples
1. Converting a 1D NumPy Array to a List
In this example, we create a 1D NumPy array and convert it into a Python list using tolist()
.
import numpy as np
# Creating a 1D NumPy array
arr = np.array([1, 2, 3, 4, 5])
# Converting the NumPy array to a Python list
list_result = arr.tolist()
# Printing the result
print(list_result)
Output:
[1, 2, 3, 4, 5]
2. Converting a 2D NumPy Array to a Nested List
Here, we convert a 2D NumPy array into a nested Python list.
import numpy as np
# Creating a 2D NumPy array
arr = np.array([[1, 2, 3],
[4, 5, 6]])
# Converting the NumPy array to a Python nested list
list_result = arr.tolist()
# Printing the result
print(list_result)
Output:
[[1, 2, 3], [4, 5, 6]]
3. Converting a 3D NumPy Array to a Nested List
This example demonstrates converting a 3D NumPy array into a deeply nested Python list.
import numpy as np
# Creating a 3D NumPy array
arr = np.array([[[1, 2], [3, 4]],
[[5, 6], [7, 8]]])
# Converting the NumPy array to a nested Python list
list_result = arr.tolist()
# Printing the result
print(list_result)
Output:
[[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
4. Converting a NumPy Array with Floating Point Numbers to a List
In this example, we convert an array containing floating-point numbers into a Python list.
import numpy as np
# Creating a NumPy array with floating-point numbers
arr = np.array([1.5, 2.3, 3.8, 4.1])
# Converting the NumPy array to a Python list
list_result = arr.tolist()
# Printing the result
print(list_result)
Output:
[1.5, 2.3, 3.8, 4.1]
5. Converting a NumPy Array with Mixed Data Types to a List
Here, we convert an array with mixed data types (integers and strings) into a Python list.
import numpy as np
# Creating a NumPy array with mixed data types
arr = np.array([1, "Hello", 3.5])
# Converting the NumPy array to a Python list
list_result = arr.tolist()
# Printing the result
print(list_result)
Output:
[1, 'Hello', 3.5]
Since NumPy arrays with mixed data types automatically convert elements to a common type (string in this case), the resulting list retains the same mixed structure.