user
Convert np.array to list
alphonsio

You can convert a NumPy array to a Python list using the .tolist() method or the list() function:

lst = np.array([1, 2, 3, 4, 5]).tolist()
lst = list(np.array([1, 2, 3, 4, 5])

You can convert a NumPy array to a list using the .tolist() method. Here's an example:

Example:

import numpy as np

# Create a NumPy array
arr = np.array([1, 2, 3, 4, 5])

# Convert to a Python list
lst = arr.tolist()

print(lst)  # Output: [1, 2, 3, 4, 5]

If you have a multi-dimensional array, .tolist() will convert it into a nested list:

import numpy as np

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

# Convert to a Python list
lst_2d = arr_2d.tolist()

print(lst_2d)  # Output: [[1, 2, 3], [4, 5, 6]]

Alternatively, you can use Python’s list() function for 1D arrays:

list(arr)  # Output: [1, 2, 3, 4, 5]

However, for multi-dimensional arrays, list() will only convert the top-level elements into lists, not the entire structure. So .tolist() is the recommended method.