flatten()/ravel()
Both turn a multi-dimensional array into a single flat line of values.
In this page:
Syntax
arr.flatten() # always a copy
arr.ravel() # view when possible
flatten()/ravel()
flatten always returns a copy, while ravel returns a view when it can. Both read elements in row-major order by default. Choose flatten when you plan to modify the result independently.
Note:
If you need a guaranteed independent array, use flatten or ravel().copy().
Example: flatten()/ravel()
import numpy as np
m = np.array([[1, 2], [3, 4]])
f = m.flatten()
r = m.ravel()
f[0] = 99
print("original after flatten edit:", m[0, 0])
r[0] = 77
print("original after ravel edit:", m[0, 0])
# Output:
# original after flatten edit: 1
# original after ravel edit: 77
Related Topics
Common Mistakes
- Modifying a raveled view and unexpectedly changing the original
- Assuming both are identical
- Forgetting the default C row order
Chapter Summary
- flatten returns a copy
- ravel returns a view when possible
- Both produce 1-D arrays
- Row-major order is the default
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: