.tolist()
The .tolist()
function in NumPy converts an array into a nested Python list and returns it. Each element in the array is converted into the closest compatible built-in Python type using the .item()
function. The attribute a.ndim
represents the number of dimensions (axes) of the array. When a.ndim
is 0, the result of the operation is a simple scalar, as the depth of the nested list is 0.
Syntax
ndarray.tolist()
ndarray
: The array to be converted.
Example
The following example creates an ndarray
named arr
and converts it into a nested Python list arr_list
using .tolist()
:
import numpy as np# Creating an arrayarr = np.uint32([1, 2])# Converting the array into a Python list using list()arr_list = list(arr)# Checking the outputprint(arr_list)# Checking the output typeprint(type(arr_list[0]))# Converting the array into a Python list using .tolist()arr_tolist = arr.tolist()# Checking the outputprint(arr_tolist)# Checking the output typeprint(type(arr_tolist[0]))
This produces the following output:
[1, 2]<class 'numpy.uint32'>[1, 2]<class 'int'>
As observed, although the resulting lists are similar, i.e., [1, 2]
, the types of their elements differ when using list()
versus .tolist()
.
Codebyte Example
Here is a codebyte example to understand the working of the .tolist()
function for converting a 2D array into a Python list:
All contributors
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python:NumPy on Codecademy
- Career path
Data Scientist: Machine Learning Specialist
Machine Learning Data Scientists solve problems at scale, make predictions, find patterns, and more! They use Python, SQL, and algorithms.Includes 27 CoursesWith Professional CertificationBeginner Friendly90 hours - Course
Learn Python 3
Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.With CertificateBeginner Friendly23 hours