← Back to NumPy Course | Chapter 5: Array Manipulation | Lesson 2 of 7

flatten()/ravel()

Both turn a multi-dimensional array into a single flat line of values.

In this page:

  1. flatten()/ravel()
Syntax
python
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()

python
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
  1. Modifying a raveled view and unexpectedly changing the original
  2. Assuming both are identical
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.