How to convert a numpy array to a list in Python?

Ways to convert numpy array to list in Python

We can use the tolist() to convert numpy array to list in Python. This function accepts a numpy array to return a list.

To convert numpy array to list in Python:

  1. Use the tolist() function.

# Convert numpy array to list
import numpy as np
# Create a numpy array
arr = np.array([12,23,31])
# Use the tolist() function
print(arr.tolist())
# Output: [12, 23, 31]    

In the above sample code, we convert array arr to a list.

A multi-dimensional array can be converted to a nested list using this function.

See the code below.

# Convert numpy array to list
import numpy as np
# Create a numpy array
arr = np.array([[12,23,31],[34,17,21]])
# Use the tolist() function
print(arr.tolist())
# Output: [[12, 23, 31], [34, 17, 21]]   

We can use the flatten() function before the tolist() function to convert a multi-dimensional array to a one-dimensional list.

See the code below.

# Convert numpy array to list
import numpy as np
# Create a numpy array
arr = np.array([[12,23,31],[34,17,21]])
# Use the flatten() function
print(arr.flatten().tolist())
# Output: [12, 23, 31, 34, 17, 21]  

We can use the traditional for loop to convert numpy array to list in Python.

To convert numpy array to list in Python:

  1. Create an empty list.
  2. Iterate over the array using the for loop.
  3. Append the elements individually to the list.

See the code below.

# Convert numpy array to list
import numpy as np
# Create a numpy array
arr = np.array([12, 23, 31])
arr_to_lst = []
for x in arr:
    arr_to_lst.append(x)
print(arr_to_lst)
# Output: [12, 23, 31]    

To conclude

This particular demonstrated two methods to convert numpy array to list in Python. The tolist() function helps to achieve this conversion. We can also get multi-dimensional arrays to one dimensional list using the flatten() method. Alternatively, the use of the for loop is also shown.

Explore more from this category at Python NumPy Arrays. Alternatively, search and view other topics at All Tutorials.