Challenge - 5 Problems
View vs Copy Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2: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)
Attempts:
2 left
💡 Hint
Remember that slicing a NumPy array creates a view, not a copy.
✗ Incorrect
In NumPy, slicing returns a view of the original array. So modifying the slice changes the original array as well.
❓ Predict Output
intermediate2: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)
Attempts:
2 left
💡 Hint
np.copy() creates a new independent array.
✗ Incorrect
np.copy() creates a new array that does not share data with the original. So modifying the copy does not affect the original array.
❓ data_output
advanced2: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)
Attempts:
2 left
💡 Hint
Check the slice indices and how many elements it covers.
✗ Incorrect
The slice arr[2:8:2] selects elements at indices 2, 4, 6 (3 elements). Modifying the view changes these 3 elements in arr.
🔧 Debug
advanced2: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)
Attempts:
2 left
💡 Hint
Check how sub_arr is created.
✗ Incorrect
Using .copy() creates a new array independent of the original. So changes to sub_arr do not affect arr.
🚀 Application
expert3: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?
Attempts:
2 left
💡 Hint
Think about which creates an independent copy before modification.
✗ Incorrect
Only option A creates a copy of the slice before modifying it, so the original array remains unchanged.