What is the numpy.ndarray.tolist() method in Python?
Overview
In Python, the ndarray.tolist() method is used to return a copy of an array as a nested list.
Syntax
ndarray.tolist()
Parameter value
The ndarray.tolist() method takes no parameter value.
Return value
The ndarray.tolist() method returns an object, a list of object, a list of list of object, or the possibly nested list of elements of an array.
Code example
import numpy as np# creating an arraymyarray = np.array([1, 2, 3, 4, 5])# implementing the ndarray.tolist() methodmylist = myarray.tolist()print(mylist)# checking for the data typeprint(type(mylist))
Explanation
- Line 1: We import the
numpymodule. - Line 4: We use the
numpy.array()function to create a1Darray variable. - Line 7: We implement the
ndarray.tolist()method on the arraymyarray. The output is assigned to a new variablemylist. - Line 9: We print the variable
mylist. - Line 12: We use the
type()function to check for the data type of the object variablemylist.