How To Convert NumPy Tuple To List In Python
Published on Aug. 22, 2023, 12:16 p.m.
To convert a NumPy tuple to a Python list, you can use the tolist()
function that is provided by the NumPy module. The tolist()
function takes a NumPy tuple as input and returns a standard Python list.
Here is an example of how to convert a NumPy tuple to a Python list using the tolist()
function:
import numpy as np
# create a NumPy tuple
np_tuple = np.array([1, 2, 3])
# convert the NumPy tuple to a Python list
py_list = np_tuple.tolist()
# print the Python list
print(py_list)
This will output [1, 2, 3]
, which is the Python list that was created from the NumPy tuple.
Note that if your NumPy array has more dimensions, you can still use the tolist()
function to convert it to a nested Python list. For example:
import numpy as np
# create a NumPy array with two dimensions
np_array = np.array([[1, 2], [3, 4]])
# convert the NumPy array to a nested Python list
py_list = np_array.tolist()
# print the nested Python list
print(py_list)
This will output [[1, 2], [3, 4]]
, which is the nested Python list that was created from the NumPy array.