flatten() behaves like ravel() in terms of the resulting shape and default reading order, but it always allocates and returns a completely new copy of the data, never a view, so modifying the flattened array is always guaranteed to leave the original array untouched. This safety comes at a small performance cost compared to ravel(), which is why flatten() is the right choice specifically when you need that independence, and ravel() is preferred when you don't.
1Understanding ndarray.flatten()
flatten() behaves like ravel() in terms of the resulting shape and default reading order, but it always allocates and returns a completely new copy of the data, never a view, so modifying the flattened array is always guaranteed to leave the original array untouched. This safety comes at a small performance cost compared to ravel(), which is why flatten() is the right choice specifically when you need that independence, and ravel() is preferred when you don't.
Choose flatten() over ravel() specifically when you plan to modify the flattened result and need a guarantee that the original array stays unaffected.
import numpy as np
matrix = np.array([[1, 2], [3, 4]])
flat = matrix.flatten()
print(flat)2Practical Example
Here is a real-world application of ndarray.flatten() showing how it is used in production NumPy code.
import numpy as np
matrix = np.array([[1, 2], [3, 4]])
flat = matrix.flatten()
flat[0] = 99
print(matrix)3Best Practices
Follow these guidelines when working with ndarray.flatten():
1. Use flatten() when the flattened array will be modified and the original array must remain untouched
2. Prefer ravel() over flatten() in performance-sensitive code where you don't need an independent copy
3. Pass order='F' explicitly if the array's column-major, Fortran-style, ordering is what your algorithm actually needs, rather than the row-major default
Tip: Choose flatten() over ravel() specifically when you plan to modify the flattened result and need a guarantee that the original array stays unaffected.
import numpy as np
matrix = np.array([[1, 2], [3, 4]])
flat = matrix.flatten()
print(flat)