Convert Python List to a NumPy Array

The following syntax can be used to convert a Python list to a numpy array:

my_array = np.array(my_list)

In this guide, you’ll see how to convert:

  1. Python list to a numpy array
  2. List of lists (multi-dimensional list) to a numpy array

(1) Convert Python List to a NumPy Array

Let’s create a simple list with 6 elements:

my_list = [10,15,20,25,30,35]

print(my_list)
print(type(my_list))

This is how the list would look like:

How to Convert a Python List to a NumPy Array

Notice that print(type(my_list)) was added at the bottom of the code in order to demonstrate that we created a list.

The goal is to convert that list to a numpy array.

To do so, you may use the template below:

my_array = np.array(my_list)

For our example, the complete code to convert the list to a numpy array is as follows:

import numpy as np

my_list = [10,15,20,25,30,35]

my_array = np.array(my_list)

print(my_array)
print(type(my_array))

As you can see, the list was converted to a numpy array:

Convert Python List to a NumPy Array

(2) Convert List of Lists to a NumPy Array

What if you have a list of lists (multi-dimensional list) and you’d like to convert it to a numpy array?

For example, let’s create the following list of lists:

my_list = [[10,15,20],[25,30,35]]

print(my_list)
print(type(my_list))

This is how the list of lists would look like:

Convert List of Lists to a NumPy Array

You can then apply the code below in order to convert the list of lists to a numpy array:

import numpy as np

my_list = [[10,15,20],[25,30,35]]

my_array = np.array(my_list)

print(my_array)
print(type(my_array))
print('Number of array dimensions: ' + str(my_array.ndim))

You’ll then get the following two-dimensional numpy array:

Two-dimensional

Additional Sources

You may visit the NumPy Documentation to learn more about creating a numpy array.

For an opposite scenario, you may check the following guide that explains how to convert a numpy array to a list.