numpy

How to convert list to Numpy array

Learn three methods to convert Python lists to NumPy arrays: np.array(), np.asarray(), and np.concatenate() for different data structures.

convert list to numpy array

Utilizing the array Method

The most straightforward way to transform a Python list into a Numpy array is by utilizing the array method. Simply pass your list as a single parameter to create the desired Numpy array.

import numpy as np

my_list = [1, 2, 3, 4, 5, 6]
my_array = np.array(my_list)
print(f"Numpy array converted "
      f"from Python list: {my_list}")

convert list to numpy array

This method provides a quick and efficient way to convert a list into a Numpy array, perfect for one-dimensional data.

See also  How to Get the Length of a NumPy Array

Leveraging the asarray Method

Another method at your disposal is the asarray method, which achieves the same result by taking your list as a single parameter.

import numpy as np

my_list = [1, 2, 3, 4, 5, 6]
my_array = np.asarray(my_list)
print(f"Numpy array converted "
      f"from Python list: {my_list}")

convert list to numpy array

The asarray method is functionally equivalent to the array method, providing you with flexibility in your conversion approach.

See also  Addressing ValueError: Resolving Shape Mismatch in NumPy Arrays

Handling Lists of Lists with the concatenate Method

When dealing with more complex tasks, such as converting a list of lists into a Numpy array, the concatenate method becomes your ally. To execute this conversion successfully, specify axis=0 as the parameter, ensuring proper concatenation.

import numpy as np

my_list = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]
my_array = np.concatenate(my_list, axis=0)
print(f"Numpy array converted "
      f"from Python list of lists: {my_list}")

convert list of lists to numpy array

This technique proves invaluable when working with multi-dimensional data structures, offering control over the axis along which concatenation occurs.