Deviate to the list() function if you want to preserve the NumPy scalar types. It keeps the NumPy types intact in the resulting list:
import numpy as np
numpy_array = np.array([np.int32(1), np.float32(2), np.complex64(3+2j)])
# Here list is the Dumbledore of Python, preserving original forms!python_list = list(numpy_array)
print(python_list) # Outputs: [numpy.int32(1), numpy.float32(2), numpy.complex64(3+2j)]
Exploring dimensions and shapes
Knowing the dimensions and shape of your array before converting is quite beneficial. Think of a multi-dimensional array conversion yielding a nested list resembling the shape of a Matrix inception.
Ensure data integrity
Confirm that your data transfer is exact. Double-check your NumPy array's dimensions and shape before converting:
import numpy as np
numpy_array_3d = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
print(f"Shape before conversion, almost like a pre-flight check: {numpy_array_3d.shape}")
converted_list = numpy_array_3d.tolist()
print(f"Depth of the converted list, did we get everything out?: {len(converted_list)}")
Flat layout methods
If you want to flatten your multi-level concert (array) before booing them off (conversion), you can call the ndarray.flatten() or np.ravel() methods:
import numpy as np
numpy_array_3d = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
# Using flatten() The 'I am bored, let's speed things up!' way flat_list = numpy_array_3d.flatten().tolist()
print(flat_list) # Outputs: [1, 2, 3, 4, 5, 6, 7, 8]# Also, np.ravel() works too. A fearless rival of flatten()flat_list_ravel = np.ravel(numpy_array_3d).tolist()
print(flat_list_ravel) # Should give the same result
More ways to Rome than one (tolist())
When .tolist() feels like a great friend but not enough to marry, alternate methods have your back.
Flattening: The B-plan
For a times when flattening needs itertools.chain.from_iterable for those 'I forgot to use NumPy' kind of days:
Had a change of heart? Turn it back into a NumPy array with np.asarray():
import numpy as np
python_list = [1, 2, 3, 4]
# Python list was fun but let's go back to NumPy arraynumpy_array = np.asarray(python_list)
print(numpy_array) # Outputs: [1, 2, 3, 4]
Shapes matter
Not happy with your array's personality (shape)? Change it:
import numpy as np
# Makeover time. Alter your array's shape as requirednumpy_array = np.arange(6).reshape(2, 3)
print(numpy_array.tolist()) # Outputs: [[0, 1, 2], [3, 4, 5]]
Say Hello to comprehensions
For times when flattening arrays is cool, but not with pandas DataFrames:
import numpy as np
import pandas as pd
df = pd.DataFrame(np.array([[1, 2, 3], [4, 5, 6]]))
# The not-so-basic way of flatteninglist_flattened = [element for sublist in df.values for element in sublist]
print(list_flattened) # Outputs: [1, 2, 3, 4, 5, 6]
Post-conversion verification steps
Always run a quick health check of type, size, and shape post-conversion: