How to convert list to a numpy array in Python?

Ways to convert list to a numpy array in Python

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

Lists represent array-like structures and are inbuilt in Python. A numpy array requires us to import numpy module and need to declare arrays before using them. A numpy array can store data efficiently and is manipulated easily for mathematical operations.

To convert list to numpy array in Python:

  1. Use the numpy.array() function.

See the code below.

# Convert list to numpy array in Python
import numpy as np
lst = [1,99,2,44,3,11]
# Use the numpy.array function to convert list to a numpy array in Python
converted_array = np.array(lst)
print(converted_array)
# Output: [ 1 99  2 44  3 11]    

The numpy.array() function can accept different objects which have an array like structure.

We can also use the numpy.asarray() function which also converts the input object to an array. The main difference is that the numpy.array() function will create a copy of the object whereas the numpy.asarray() function will not create a copy by default.

To create a copy of the object using the numpy.asarray() function, set the copy parameter as True.

To convert list to numpy array in Python:

  1. Use the numpy.asarray() function.

See the code below.

# Convert list to numpy array in Python
import numpy as np
lst = [1,99,2,44,3,11]
# Use the numpy.asarray function to convert list to a numpy array in Python
converted_array = np.asarray(lst)
print(converted_array)
# Output: [ 1 99  2 44  3 11]  

To conclude

This tutorial discussed how to convert list to numpy array in Python. We demonstrate this by using the numpy.array and numpy.asarray functions.

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