Python – Convert NumPy Array to List

Filed Under: Python
Numpy Array To List

We can use numpy ndarray tolist() function to convert the array to a list. If the array is multi-dimensional, a nested list is returned. For one-dimensional array, a list with the array elements is returned.

NumPy Array to List

The tolist() function doesn’t accept any argument. It’s a simple way to convert an array to a list representation.

1. Converting one-dimensional NumPy Array to List


import numpy as np

# 1d array to list
arr = np.array([1, 2, 3])
print(f'NumPy Array:\n{arr}')

list1 = arr.tolist()
print(f'List: {list1}')

Output:


NumPy Array:
[1 2 3]
List: [1, 2, 3]

2. Converting multi-dimensional NumPy Array to List


import numpy as np

# 2d array to list
arr = np.array([[1, 2, 3], [4, 5, 6]])

print(f'NumPy Array:\n{arr}')

list1 = arr.tolist()

print(f'List: {list1}')

Output:


NumPy Array:
[[1 2 3]
 [4 5 6]]
List: [[1, 2, 3], [4, 5, 6]]

Reference: API Doc

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages