ravel vs flatten
Turn any multi-dimensional array into 1D with ravel() or flatten() — and understand why one returns a view and the other always a copy.
Watch the lesson
1 video on CodeWithMunnaX
Often you need all the numbers in one straight line: to sort every score of the squad, to count unique values, or to feed data into a function that wants 1D input. NumPy gives you two methods that look identical — ravel() and flatten() — but behave very differently when you modify the result.
Definition
Flattening converts an array of any shape into a 1D array containing all its elements (row by row by default).
flatten()always returns a new copy of the data.ravel()returns a view of the original data whenever possible (and a copy only when it has to).
- 1D — a
(4, 3)array becomes(12,). - Copy — separate memory. Changing the flattened array never affects the original.
- View — the same memory seen through a new shape. Changing the raveled array changes the original too.
- Whenever possible — if the original's elements are not laid out contiguously in memory (e.g. after a transpose or a step slice),
ravelsilently falls back to making a copy.
Syntax
python
a.flatten(order="C") # always a copy (method only)
a.ravel(order="C") # a view if possible
np.ravel(a, order="C") # function form of ravel
a.reshape(-1) # same behaviour as ravel()| Parameter | Meaning | Default |
|---|---|---|
order | "C" = row by row, "F" = column by column, "A"/"K" = follow memory layout | "C" |
Example — both give the same values
python
import numpy as np
scores = np.array([
[72, 45, 88],
[56, 0, 74],
[45, 32, 0],
])
print("ravel :", scores.ravel())
print("flatten:", scores.flatten())
print("F order:", scores.ravel(order="F"))text
ravel : [72 45 88 56 0 74 45 32 0]
flatten: [72 45 88 56 0 74 45 32 0]
F order: [72 56 45 45 0 32 88 74 0]How it works: both read the 3×3 table row by row into 9 values. With order="F" they read down each column instead (Virat-Rohit-Hardik for match 1, then match 2, …).
Example — the difference: modify the result
This is the notebook's demo, done safely — each method gets its own fresh array, so the effect is easy to see:
python
import numpy as np
scores = np.array([[72, 45, 88], [56, 0, 74]])
flat_copy = scores.flatten()
flat_copy[0] = 999
print("after editing flatten() result:", scores[0, 0], "(original unchanged)")
scores = np.array([[72, 45, 88], [56, 0, 74]])
flat_view = scores.ravel()
flat_view[0] = 888
print("after editing ravel() result :", scores[0, 0], "(original CHANGED)")
print(scores)text
after editing flatten() result: 72 (original unchanged)
after editing ravel() result : 888 (original CHANGED)
[[888 45 88]
[ 56 0 74]]How it works: flatten() copied the 6 numbers into new memory, so writing 999 touches only the copy. ravel() returned a view of the same memory, so writing 888 into position 0 of the view writes into scores[0, 0].
Example — when ravel has to copy
python
import numpy as np
scores = np.array([[72, 45, 88], [56, 0, 74]])
r1 = scores.ravel() # contiguous -> view
r2 = scores.T.ravel() # transposed -> elements not in order -> copy
r3 = scores.flatten() # always a copy
print("ravel shares memory :", np.shares_memory(scores, r1))
print("ravel of .T shares memory :", np.shares_memory(scores, r2))
print("flatten shares memory :", np.shares_memory(scores, r3))
print("r2 values:", r2)text
ravel shares memory : True
ravel of .T shares memory : False
flatten shares memory : False
r2 values: [72 56 45 0 88 74]How it works: np.shares_memory(x, y) returns True if the two arrays use the same memory. The transposed array reads values column by column, which is not the order they sit in memory, so ravel cannot give a simple view and quietly makes a copy.
Comparison — ravel vs flatten
ravel() | flatten() | |
|---|---|---|
| Returns | a view when possible, otherwise a copy | always a copy |
| Speed / memory | faster, no extra memory (when a view) | slower, uses extra memory |
| Modifying the result | may change the original | never changes the original |
| Available as | method a.ravel() and function np.ravel(a) | method a.flatten() only |
| Works on lists? | np.ravel([[1, 2], [3, 4]]) ✅ | lists have no .flatten() |
| Same as | a.reshape(-1) | a.reshape(-1).copy() |
| Use when | read-only use, big data, speed matters | you will modify the result and want the original safe |
Tip — rule of thumb from the course: use
.flatten()when you want a safe, independent copy. Use.ravel()when you only need to read the values, or you understand it may alias the original.
Common mistakes
- ❌ Modifying a
ravel()result and being surprised the original changed. ✅ Useflatten()(orravel().copy()) if you will modify it. - ❌ Assuming
ravel()is always a view. ✅ It's a view only when possible; check withnp.shares_memory. - ❌
scores.flat()→TypeError. ✅a.flatis an iterator attribute (no brackets), not a flattening method; useravel()/flatten()for an array. - ❌ Flattening when you didn't need to — e.g.
scores.flatten().max(). ✅scores.max()already works over the whole array.
Interview tip
Q: What is the difference between ravel() and flatten()?
A: Both return a 1D version of the array. flatten() always allocates a new copy, so changes to it never affect the original. ravel() returns a view of the original memory when possible (faster, no extra memory), so changes to it can modify the original; if the data isn't contiguous (e.g. after a transpose) ravel() returns a copy.
Key points to remember
- Flattening turns an array of any shape into 1D, reading row by row by default.
- flatten() always returns a new, independent copy.
- ravel() returns a view whenever possible — editing it can change the original array.
- ravel() falls back to a copy when the data isn't contiguous (e.g. after .T or a step slice).
- np.shares_memory(a, b) tells you whether two arrays use the same memory.
- ravel() is faster and memory-free; flatten() is safer when you plan to modify the result.
- a.reshape(-1) behaves like ravel(); np.ravel() also works on plain lists.
Try it yourself
ravel and flatten give the same values
Copy vs view in action
When ravel copies
Practice: squad's top 3 scores
Revision Flashcards
Tap a card to flip it and see the answer.
