9951 explained code solutions for 126 technologies


python-scipyHow do I convert a Python numpy array to a list?


The easiest way to convert a Python numpy array to a list is using the tolist() function. This function will convert the array to a list and return it.

Example

import numpy as np

a = np.array([[1,2,3], [4,5,6]])

list_a = a.tolist()

print(list_a)

Output example

[[1, 2, 3], [4, 5, 6]]

The tolist() function takes the array and converts it into a list of the same elements. The elements are grouped by their original position in the array.

Code explanation

  1. Importing the numpy library as np: import numpy as np
  2. Creating the array: a = np.array([[1,2,3], [4,5,6]])
  3. Converting the array to a list: list_a = a.tolist()
  4. Printing the list: print(list_a)

Helpful links

Edit this code on GitHub