numpy.ndarray.tolist()
The numpy.ndarray.tolist()
function returns the array as a list. The list contains the same data as the original array, but with each axis chopped up and placed in a nested list.
Syntax
numpy.ndarray.tolist()
Example
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
list_arr = arr.tolist()
print(list_arr)
Output:
[[1, 2, 3], [4, 5, 6]]
Explanation
In the above example, we have imported the numpy library and created a two-dimensional array using np.array()
. We then called the tolist()
method on the NumPy array to convert the array into a standard Python list. The tolist()
method returns a nested list where each inner list represents a row of the original NumPy array.
Use
The tolist()
method is particularly useful when dealing with arrays and lists in Python, as it allows for easy conversion between the two data types. It can be especially useful when working with packages that only support lists, such as certain plotting packages.
Important Points
- The original NumPy array remains unchanged when calling
tolist()
. - The
tolist()
method can be used on both one-dimensional and multi-dimensional NumPy arrays.
Summary
The numpy.ndarray.tolist()
method is used to convert a NumPy array into a nested list. This function can be useful when working with packages that require standard Python lists, as it allows for easy conversion between NumPy arrays and Python lists. The original array remains unchanged when calling tolist()
.