Challenge - 5 Problems
Flatten and Ravel Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of flatten() vs ravel() on a 2D array
What is the output of the following code snippet?
NumPy
import numpy as np arr = np.array([[1, 2], [3, 4]]) flat = arr.flatten() rav = arr.ravel() flat[0] = 100 rav[1] = 200 print(arr) print(flat) print(rav)
Attempts:
2 left
💡 Hint
Remember that flatten() returns a copy, while ravel() returns a view when possible.
✗ Incorrect
Modifying the flattened array does not affect the original because flatten() returns a copy. Modifying the raveled array affects the original because ravel() returns a view when possible.
❓ data_output
intermediate1:30remaining
Shape of arrays after flatten() and ravel()
Given the code below, what are the shapes of flat and rav?
NumPy
import numpy as np arr = np.arange(12).reshape(3,4) flat = arr.flatten() rav = arr.ravel() print(flat.shape) print(rav.shape)
Attempts:
2 left
💡 Hint
Both flatten() and ravel() convert the array to 1D.
✗ Incorrect
Both flatten() and ravel() return 1D arrays, so their shape is (12,).
🔧 Debug
advanced1:30remaining
Why does modifying ravel() output change the original array?
Consider this code:
import numpy as np
arr = np.array([[5, 6], [7, 8]])
r = arr.ravel()
r[0] = 100
print(arr)
Why does arr change after modifying r?
NumPy
import numpy as np arr = np.array([[5, 6], [7, 8]]) r = arr.ravel() r[0] = 100 print(arr)
Attempts:
2 left
💡 Hint
Think about whether ravel() returns a copy or a view.
✗ Incorrect
ravel() returns a view when possible, so modifying r changes the original array arr.
🧠 Conceptual
advanced1:30remaining
Memory usage difference between flatten() and ravel()
Which statement about memory usage is true when comparing flatten() and ravel()?
Attempts:
2 left
💡 Hint
Check which method returns a copy and which returns a view.
✗ Incorrect
flatten() always returns a copy, so it uses more memory. ravel() returns a view when possible, so it uses less memory.
🚀 Application
expert2:30remaining
Choosing flatten() or ravel() for safe modification
You have a large 2D numpy array and want to create a 1D version to modify without changing the original array. Which method should you use and why?
Attempts:
2 left
💡 Hint
Think about whether you want changes to affect the original array or not.
✗ Incorrect
flatten() returns a copy, so modifying it does not affect the original array. ravel() returns a view, so modifying it changes the original array.