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 array
myarray = np.array([1, 2, 3, 4, 5])
# implementing the ndarray.tolist() method
mylist = myarray.tolist()
print(mylist)
# checking for the data type
print(type(mylist))

Explanation

  • Line 1: We import the numpy module.
  • Line 4: We use the numpy.array() function to create a 1D array variable.
  • Line 7: We implement the ndarray.tolist() method on the array myarray. The output is assigned to a new variable mylist.
  • Line 9: We print the variable mylist.
  • Line 12: We use the type() function to check for the data type of the object variable mylist.

Free Resources