Convert Python List to NumPy Array

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

Case 1: Convert Python List to a NumPy Array

To start, 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:

[10, 15, 20, 25, 30, 35]
<class 'list'>

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

The goal is to convert that list to a NumPy array using:

my_array = np.array(my_list)

For our example:

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:

[10 15 20 25 30 35]
<class 'numpy.ndarray'>

Case 2: Convert a List of Lists to a NumPy Array

What if you want to convert a list of lists to a NumPy array?

For example, 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:

[[10, 15, 20], [25, 30, 35]]
<class 'list'>

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:

[[10 15 20]
 [25 30 35]]
<class 'numpy.ndarray'>
Number of array dimensions: 2 

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

Leave a Comment