With NumPy, np.array
objects can be converted to a list with the tolist()
function. The tolist()
function doesn’t accept any arguments. If the array is one-dimensional, a list with the array elements is returned. For a multi-dimensional array, a nested list is returned.
In order to complete this tutorial, you will need:
pip
to install packages. And familiarity with coding in Python. How to Code in Python 3 series or using VS Code for Python.This tutorial was tested with Python 3.9.6 and NumPy 1.23.3.
Let’s construct a one-dimensional array of [1, 2, 3]
:
import numpy as np
# 1d array to list
arr_1 = np.array([1, 2, 3])
print(f'NumPy Array:\n{arr_1}')
This code will output:
NumPy Array:
[1 2 3]
Now, let’s use tolist()
:
import numpy as np
# 1d array to list
arr_1 = np.array([1, 2, 3])
print(f'NumPy Array:\n{arr_1}')
list_1 = arr_1.tolist()
print(f'List: {list_1}')
This new code will output:
List: [1, 2, 3]
The array has been converted from numpy
scalars to Python scalars.
Let’s construct a multi-dimensional array of [ [1, 2, 3], [4, 5, 6] ]
:
import numpy as np
# 2d array to list
arr_2 = np.array([[1, 2, 3], [4, 5, 6]])
print(f'NumPy Array:\n{arr_2}')
This code will output:
NumPy Array:
[[1 2 3]
[4 5 6]]
Now, let’s use tolist()
:
import numpy as np
# 2d array to list
arr_2 = np.array([[1, 2, 3], [4, 5, 6]])
print(f'NumPy Array:\n{arr_2}')
list_2 = arr_2.tolist()
print(f'List: {list_2}')
This new code will output:
List: [[1, 2, 3], [4, 5, 6]]
The array has been converted from numpy
scalars to Python scalars.
In this article, you learned how to use tolist()
to convert np.array
objects to lists. It is applicable to one-dimensional and multi-dimensional arrays.
References
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
Sign up for Infrastructure as a Newsletter.
Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.
thanks for your help man , great buddy . actualluy i was working in opencv2 and the value was in array and i cant turn it until i found that it was a numpy array . hahahahahah
- akshit
Thank you for this i can convert ndarray to list obj
- arnaldo