numpy.ndarray.tolist() in Python

The numpy module provides a function numpy.ndarray.tolist(), used to convert the data elements of an array into a list. This function returns the array as an a.ndim- levels deep nested list of Python scalars.

In simple words, this function returns a copy of the array elements as a Python list. The elements are converted to the nearest compatible built-in Python type through the item function. When 'a.ndim' is 0, then the depth of the list is 0, and it will be a simple Python scalar, not any list.

numpy.ndarray.tolist

Syntax

Parameters

This function has no arguments or parameters.

Returns: y: object, or list of object, or list of object

This function returns the possibly nested list of array elements.

Note
We can re-create the array via a=np.array(a.tolist()), however it can sometimes lose precision.

Example 1:

If we will use a.tolist() for a 1D array then it will be almost the same as list(a), except that tolist converts numpy scalars to Python scalars.

Output:

array([6, 2], dtype=uint32)
[6, 2]
<type 'numpy.uint32'>
[6L, 2L]
<type 'long'>

In the above code

  • We have imported numpy with alias name np.
  • We have created an array 'a' using np.uint32() function.
  • We have declared the variable 'a_list' and assigned the returned value of the list() function.
  • We tried to print the value of 'a', 'a_list', and type of a_list.
  • We have declared the variable a_tolist and assigned the returned value of ndarray.tolist().
  • Lastly, we tried to print the type and the value of 'a_tolist'.

In the output, it shows a list and the type whose elements are transformed from the source array.

Example 2:

For a 2-dimensional array, tolist is applied recursively.

Output:

array([[11, 21],
       	[31, 41]])
[[11, 21], [31, 41]]

In the above code

  • We have imported numpy with alias name np.
  • We have created a 2-dimensional array 'a' using the np.array() function.
  • We have declared the variable 'b' and assigned the returned value of a.tolist() function.
  • Lastly, we tried to print the value of 'b'.

In the output, it shows a list whose elements are transformed from the source array.

Example 3:

Output:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: iteration over a 0-d array
5

Next Topicnumpy.dot()




Latest Courses