Thursday, December 26, 2024
Google search engine
HomeLanguagesHow to convert NumPy array to list ?

How to convert NumPy array to list ?

To convert NumPy arrays to a Python list. We can convert the Numpy array to the list by 2 different methods, we can have a list of data elements that is converted from an array using these methods:

Using type casting to Converting Numpy array to list

Here we are creating a Numpy array using the np.array and printing the array before the conversion and after the conversion using Python typecasting to list using list() function.

Python3




# import module
import numpy as np
 
# create array
arr = np.array([1, 2, 4, 5])
print("Before conversion: ", arr)
print(type(arr))
 
# Converting numpy to list
arr = list(arr)
print("\nAfter conversion: ", type(arr))
print(arr)


Output:

Before conversion:  [1 2 4 5]
<class 'numpy.ndarray'>

After conversion:  <class 'list'>
[1, 2, 4, 5]

Using tolist() Converting Numpy array to list

Example 1: With one Dimensional Array

Python3




# import module
import numpy as np
 
# create array
print("\nArray:")
arr = np.array([1, 2, 4, 5]) 
print(arr)
print(type(arr))
 
# apply method
lis = arr.tolist()
 
# display list
print("\nList:")
print(lis)
print(type(lis))


Output:

convert NumPy array to list

 

Example 2: With Multidimensional Array

Python3




# import module
import numpy as np
 
# create array
print("\nArray:")
arr = np.array([[1, 2, 3],
                [4, 5, 6],
                [7, 8, 9]])
print(arr)
print(type(arr))
 
# apply method
lis = arr.tolist()
 
# display list
print("\nList:")
print(lis)
print(type(lis))


Output:

convert NumPy array to list

 

RELATED ARTICLES

Most Popular

Recent Comments