We can use the 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 importnumpy
module and need to declare arrays before using them. Anumpy
To convert list to numpy
array in Python:
-
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 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 thecopy
parameter as True.
To convert list to numpy
array in Python:
-
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
Explore more from this category at Python NumPy Arrays. Alternatively, search and view other topics at All Tutorials.