0
0
NumpyHow-ToBeginner ยท 2 min read

Numpy How to Convert Array to List with Example

You can convert a numpy array to a list by using the tolist() method like my_list = my_array.tolist().
๐Ÿ“‹

Examples

Input[1, 2, 3]
Output[1, 2, 3]
Input[[1, 2], [3, 4]]
Output[[1, 2], [3, 4]]
Input[]
Output[]
๐Ÿง 

How to Think About It

To convert a numpy array to a list, think about turning the array's elements into a regular Python list structure. The numpy array has a built-in method called tolist() that does this conversion easily, preserving the shape and elements as nested lists if needed.
๐Ÿ“

Algorithm

1
Get the numpy array as input.
2
Call the <code>tolist()</code> method on the array.
3
Return the resulting Python list.
๐Ÿ’ป

Code

python
import numpy as np

my_array = np.array([[1, 2], [3, 4]])
my_list = my_array.tolist()
print(my_list)
Output
[[1, 2], [3, 4]]
๐Ÿ”

Dry Run

Let's trace converting the numpy array [[1, 2], [3, 4]] to a list.

1

Start with numpy array

my_array = np.array([[1, 2], [3, 4]])

2

Call tolist() method

my_list = my_array.tolist()

3

Resulting Python list

my_list = [[1, 2], [3, 4]]

StepActionValue
1Input array[[1, 2], [3, 4]]
2Call tolist()Convert to list
3Output 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

Using list() on 1D array
python
import numpy as np
my_array = np.array([1, 2, 3])
my_list = list(my_array)
print(my_list)
Works only for 1D arrays; does not preserve nested structure for multi-dimensional arrays.
Using a list comprehension
python
import numpy as np
my_array = np.array([1, 2, 3])
my_list = [x for x in my_array]
print(my_list)
Also works only for 1D arrays; more manual and less efficient than tolist().
โšก

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.

ApproachTimeSpaceBest For
tolist()O(n)O(n)All array shapes, easy and reliable
list() on 1D arrayO(n)O(n)Only 1D arrays, simple cases
List comprehensionO(n)O(n)Only 1D arrays, manual control
๐Ÿ’ก
Use tolist() for a clean and reliable conversion of any numpy array to a Python list.
โš ๏ธ
Trying to use list() on multi-dimensional arrays, which results in a list of numpy arrays, not nested lists.