0
0
NumPydata~20 mins

View vs copy behavior in NumPy - Practice Questions

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
View vs Copy Mastery
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 NumPy slice?
Consider the following code where we create a NumPy array and then slice it. What will be the output after modifying the slice?
NumPy
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
slice_arr = arr[1:4]
slice_arr[0] = 10
print(arr)
A[ 1 2 3 4 5]
B[ 1 10 3 4 5]
C[ 1 10 2 4 5]
D[10 2 3 4 5]
Attempts:
2 left
💡 Hint
Remember that slicing a NumPy array creates a view, not a copy.
Predict Output
intermediate
2:00remaining
What happens when using np.copy() on a slice?
Given the code below, what will be printed after modifying the copied slice?
NumPy
import numpy as np
arr = np.array([5, 6, 7, 8, 9])
copied_slice = np.copy(arr[1:4])
copied_slice[0] = 100
print(arr)
A[ 5 6 100 8 9]
B[ 5 100 7 8 9]
C[100 6 7 8 9]
D[ 5 6 7 8 9]
Attempts:
2 left
💡 Hint
np.copy() creates a new independent array.
data_output
advanced
2:00remaining
How many elements are changed in the original array after this operation?
What is the number of elements in the original array 'arr' that are modified after running this code?
NumPy
import numpy as np
arr = np.arange(10)
view = arr[2:8:2]
view[:] = -1
print(arr)
A3
B6
C5
D4
Attempts:
2 left
💡 Hint
Check the slice indices and how many elements it covers.
🔧 Debug
advanced
2:00remaining
Why does this code not modify the original array?
Examine the code below. Why does modifying 'sub_arr' not change 'arr'?
NumPy
import numpy as np
arr = np.array([10, 20, 30, 40, 50])
sub_arr = arr[1:4].copy()
sub_arr[0] = 999
print(arr)
ABecause the slice indices are incorrect and no elements are selected.
BBecause arr is immutable and cannot be changed.
CBecause sub_arr is a copy, not a view, so changes don't affect arr.
DBecause sub_arr is a view but changes are buffered and not applied immediately.
Attempts:
2 left
💡 Hint
Check how sub_arr is created.
🚀 Application
expert
3:00remaining
Identify the correct way to modify a NumPy array without affecting the original
You want to modify a subset of a NumPy array without changing the original array. Which option correctly achieves this?
A
subset = arr[2:5].copy()
subset[0] = 100
B
subset = arr[2:5]
subset[0] = 100
C
subset = arr[2:5]
arr[2] = 100
D
subset = arr.copy()[2:5]
subset[0] = 100
Attempts:
2 left
💡 Hint
Think about which creates an independent copy before modification.