Numpy How to Convert Array to List with Example
tolist() method like my_list = my_array.tolist().Examples
How to Think About It
tolist() that does this conversion easily, preserving the shape and elements as nested lists if needed.Algorithm
Code
import numpy as np my_array = np.array([[1, 2], [3, 4]]) my_list = my_array.tolist() print(my_list)
Dry Run
Let's trace converting the numpy array [[1, 2], [3, 4]] to a list.
Start with numpy array
my_array = np.array([[1, 2], [3, 4]])
Call tolist() method
my_list = my_array.tolist()
Resulting Python list
my_list = [[1, 2], [3, 4]]
| Step | Action | Value |
|---|---|---|
| 1 | Input array | [[1, 2], [3, 4]] |
| 2 | Call tolist() | Convert to list |
| 3 | Output list | [[1, 2], [3, 4]] |
Why This Works
Step 1: Use of tolist()
The tolist() method converts the numpy array into a nested Python list, preserving the shape.
Step 2: Preserves nested structure
If the array is multi-dimensional, tolist() returns nested lists matching the array's dimensions.
Step 3: Easy conversion
This method is simple and direct, requiring no loops or manual conversion.
Alternative Approaches
import numpy as np my_array = np.array([1, 2, 3]) my_list = list(my_array) print(my_list)
import numpy as np my_array = np.array([1, 2, 3]) my_list = [x for x in my_array] print(my_list)
Complexity: O(n) time, O(n) space
Time Complexity
The tolist() method visits each element once to build the list, so it takes linear time relative to the number of elements.
Space Complexity
It creates a new list structure with the same number of elements, so space usage is also linear.
Which Approach is Fastest?
The tolist() method is optimized and works for all array shapes, making it the best general choice compared to manual methods.
| Approach | Time | Space | Best For |
|---|---|---|---|
| tolist() | O(n) | O(n) | All array shapes, easy and reliable |
| list() on 1D array | O(n) | O(n) | Only 1D arrays, simple cases |
| List comprehension | O(n) | O(n) | Only 1D arrays, manual control |
tolist() for a clean and reliable conversion of any numpy array to a Python list.list() on multi-dimensional arrays, which results in a list of numpy arrays, not nested lists.