Search code examples
pythonlistnumpynumpy-ndarray

Convert NumPy array to Python list


How do I convert a NumPy array into a Python List?


Solution

  • Use tolist():

    >>> import numpy as np
    >>> np.array([[1,2,3],[4,5,6]]).tolist()
    [[1, 2, 3], [4, 5, 6]]
    

    Note that this converts the values from whatever numpy type they may have (e.g. np.int32 or np.float32) to the "nearest compatible Python type" (in a list). If you want to preserve the numpy data types, you could call list() on your array instead, and you'll end up with a list of numpy scalars. (Thanks to Mr_and_Mrs_D for pointing that out in a comment.)