How to convert list to Numpy array

In this tutorial, we’ll explore three distinct approaches for converting Python lists into NumPy arrays. This conversion is a fundamental operation when working with data in the NumPy library, allowing for more 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  How to Append to an Empty Array in Numpy (with Examples)

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 use numpy mgrid

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 Generate Sequence Arrays in Python with Numpy arange

By mastering these three methods, you’ll be well-equipped to convert Python lists into Numpy arrays efficiently, regardless of the complexity of your data.