How to convert list to Numpy array

We’ll explore three distinct approaches to converting Python lists into NumPy arrays. This operation is fundamental when working with NumPy, allowing for efficient data manipulation and analysis.

convert list to numpy array

There are 3 different ways to convert Python 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  Converting Tensors to NumPy Arrays in Python

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  How to sum up array in Numpy?

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.

See also  How to check if array is empty?