You can use tolist() in order to convert a numpy array to a list in Python:
my_list = my_array.tolist()
Below are the steps to convert a numpy array to a list (as well as to a list of lists) using practical examples.
Steps to Convert NumPy Array to a List in Python
Step 1: Create a NumPy array
To start with a simple example, let’s create the following NumPy array:
import numpy as np my_array = np.array([11,22,33,44,55,66]) print(my_array) print(type(my_array))
Run the code in Python, and you’ll get the following numpy array:
[11 22 33 44 55 66]
<class 'numpy.ndarray'>
Notice that print(type(my_array)) was added at the bottom of the code in order to demonstrate that we got a numpy array.
Step 2: Convert the NumPy array to a List
You may use tolist() to convert the numpy array to a list in Python:
my_list = my_array.tolist()
For our example, the complete code to convert the numpy array to a list is as follows:
import numpy as np my_array = np.array([11,22,33,44,55,66]) my_list = my_array.tolist() print(my_list) print(type(my_list))
As you can see, the numpy array was converted to a list:
[11, 22, 33, 44, 55, 66]
<class 'list'>
Convert NumPy Array to a List of Lists
In this section, you’ll see how to convert two-dimensional array to a list of lists.
To begin, let’s create the two-dimensional numpy array:
import numpy as np my_array = np.array([[11,22,33],[44,55,66]]) print(my_array) print(type(my_array)) print('Number of array dimensions: ' + str(my_array.ndim))
Here is the array that you’ll get:
[[11 22 33]
[44 55 66]]
<class 'numpy.ndarray'>
Number of array dimensions: 2
You can then use tolist() to convert the array to a list of lists:
import numpy as np my_array = np.array([[11,22,33],[44,55,66]]) my_list = my_array.tolist() print(my_list) print(type(my_list))
Once you run the code, you’ll get the following result:
[[11, 22, 33], [44, 55, 66]]
<class 'list'>
You can read more about tolist() by visiting the NumPy Documentation.
For an opposite scenario, you may check the following guide that explains how to convert a list to a numpy array.