0
0
NumPydata~20 mins

Indexing returns views not copies in NumPy - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
View vs Copy Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of modifying a view created by slicing a NumPy array?
Consider the following code where we create a NumPy array and slice it. What will be the content of the original array after modifying the slice?
NumPy
import numpy as np
arr = np.array([10, 20, 30, 40, 50])
slice_arr = arr[1:4]
slice_arr[0] = 99
print(arr)
A[10 99 30 40 50]
B[10 20 30 40 50]
C[10 99 99 40 50]
D[10 20 99 40 50]
Attempts:
2 left
💡 Hint
Remember that slicing a NumPy array returns a view, not a copy.
Predict Output
intermediate
2:00remaining
What happens when you modify a copy created by fancy indexing in NumPy?
Look at this code where we use fancy indexing to select elements. What will be the output of the original array after modifying the selected elements?
NumPy
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
selected = arr[[1, 3]]
selected[0] = 99
print(arr)
A[1 99 3 4 5]
B[1 2 99 4 5]
C[1 2 3 4 5]
D[1 99 3 99 5]
Attempts:
2 left
💡 Hint
Fancy indexing returns a copy, not a view.
🔧 Debug
advanced
2:30remaining
Why does modifying a slice not change the original array here?
This code tries to modify a slice of a 2D NumPy array but the original array remains unchanged. What is the reason?
NumPy
import numpy as np
arr = np.array([[1, 2], [3, 4], [5, 6]])
slice_arr = arr[[0, 2]]
slice_arr[0, 0] = 99
print(arr)
ABecause NumPy arrays are immutable.
BBecause the array is 2D, slices always return copies.
CBecause the assignment syntax is incorrect.
DBecause fancy indexing returns a copy, not a view.
Attempts:
2 left
💡 Hint
Check the type of indexing used to create the slice.
data_output
advanced
2:00remaining
How many elements are changed in the original array after modifying a boolean mask view?
Given this code, how many elements in the original array are changed after modifying the masked view?
NumPy
import numpy as np
arr = np.array([5, 10, 15, 20, 25])
mask = arr > 10
view = arr[mask]
view[:] = 0
print(arr)
A0
B2
C3
D5
Attempts:
2 left
💡 Hint
Boolean indexing returns a copy, not a view.
🚀 Application
expert
3:00remaining
How to safely modify a subset of a NumPy array without affecting the original?
You want to modify a subset of a NumPy array without changing the original array. Which approach below correctly achieves this?
A
subset = arr[[1, 2, 3]]
subset[0] = 100
B
subset = arr[1:4].copy()
subset[0] = 100
C
subset = arr[1:4]
subset[0] = 100
D
subset = arr
subset[1] = 100
Attempts:
2 left
💡 Hint
Think about when views or copies are created and how to avoid changing the original.