How to convert list to NumPy array in Python

You can convert the list to a NumPy array in Python with the following methods. If you want to learn Python, I highly recommend reading This Book.

How to convert list to NumPy array in Python
How to convert list to NumPy array in Python

If NumPy is not installed, first install it using this code.

pip install numpy

Method 1: np.array()

# Import the NumPy Library
import numpy as np 
  
# Initialize the List with variable a
a = [5, 10, 15, 35, 9, 12, 7] 
  
# Convert the list to NumPy array
b = np.array(a) 

# Print the type of a
print(type(a))

# Print the type of b
print(type(b))

Output:

<class 'list'>
<class 'numpy.ndarray'>

Method 2: np.asarray()

# Import the NumPy Library
import numpy as np 
  
# Initialize the List with variable a
a = [5, 10, 15, 35, 9, 12, 7] 
  
# Convert the list to NumPy array
b = np.asarray(a) 

# Print the type of a
print(type(a))

# Print the type of b
print(type(b))

Output:

<class 'list'>
<class 'numpy.ndarray'>

Free Learning Resources

Leave a Comment

Your email address will not be published.