In this post, we will learn how to convert numpy array to list with detailed explanation and example.
Basically, there are four different ways to convert a numpy array to a Python list.
- Using the Numpy
tolist()
method (simplest and easiest way). - Using
list()
function - Using for-loop
- Using list comprehension
Let’s see all four ways one by one with the help of example.
To learn the Numpy library check out this article 👉 Learn Python NumPy Library with Simple Example
Using the Numpy tolist()
method
Numpy provides a built-in method called tolist()
, which converts a NumPy array to a Python list. Let’s see this with an example.
import numpy as np
arr = np.array([1,2,3,4,5]) # create numpy array
print(type(arr)) # check type
print(arr)
my_list = arr.tolist() # convert numpy array to a list
print(type(my_list)) # checking type
print(my_list)
Output:
<class 'numpy.ndarray'>
[1 2 3 4 5]
<class 'list'>
[1, 2, 3, 4, 5]
Using list()
function
We can also use the list()
function in Python to convert a NumPy array to a list. After the tolist()
method, this is one of the most common ways to convert a NumPy array to a list.
import numpy as np
arr = np.array([2,4,6,8,10]) # create numpy array
print(type(arr)) # check type
print(arr)
lst = list(arr) # convert Numpy array to a list
print(type(lst)) # check type
print(lst)
Output:
<class 'numpy.ndarray'>
[ 2 4 6 8 10]
<class 'list'>
[2, 4, 6, 8, 10]
Using For-loop
Instead of using built-in functions or methods, you can convert a NumPy array to a list using a for loop.
import numpy as np
arr = np.array([1,2,3,5,7]) # create numpy array
print(type(arr)) # check type
print(arr)
# ---convert Numpy array to a list---
lst = [] # create a empty list
# Using for loop iterate in Numpy array (arr)
for i in arr:
lst.append(i) # add numpy elements to a empty list
print(type(lst)) # check type
print(lst)
Output:
<class 'numpy.ndarray'>
[1 2 3 5 7]
<class 'list'>
[1, 2, 3, 5, 7]
Using list comprehension
For-loop increases the number of lines in code. So instead of using a for-loop to convert a NumPy array to a list, we can also use list comprehension. it converts a NumPy array to a list in just one line.
import numpy as np
arr = np.array([1,2,3,5,7,9,11]) # create numpy array
print(type(arr)) # check type
print(arr)
# ---convert Numpy array to a list using list comprehension---
lst = [i for i in arr]
print(type(lst))
print(lst)
Output:
<class 'numpy.ndarray'>
[ 1 2 3 5 7 9 11]
<class 'list'>
[1, 2, 3, 5, 7, 9, 11]
In conclusion, these are four different ways to convert a NumPy array to a list. I hope this post adds some value to your life. Thank you for reading, and see you in the next article.