0
0
NumPydata~20 mins

Why indexing matters in NumPy - Challenge Your Understanding

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Indexing Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of slicing vs. fancy indexing in NumPy
What is the output of the following code snippet?
NumPy
import numpy as np
arr = np.array([10, 20, 30, 40, 50])
slice_view = arr[1:4]
slice_view[0] = 99
print(arr)
fancy_index = arr[[1, 2, 3]]
fancy_index[0] = 77
print(arr)
A[10 20 30 40 50]\n[10 20 30 40 50]
B[10 20 30 40 50]\n[10 77 30 40 50]
C[10 99 30 40 50]\n[10 99 30 40 50]
D[10 99 30 40 50]\n[10 20 30 40 50]
Attempts:
2 left
💡 Hint
Remember that slicing returns a view, while fancy indexing returns a copy.
data_output
intermediate
1:30remaining
Number of elements selected by boolean indexing
Given the array and boolean mask below, how many elements are selected?
NumPy
import numpy as np
arr = np.array([5, 10, 15, 20, 25, 30])
mask = arr > 15
selected = arr[mask]
print(len(selected))
A3
B4
C2
D5
Attempts:
2 left
💡 Hint
Count how many values in arr are greater than 15.
🔧 Debug
advanced
1:30remaining
Why does this indexing code raise an error?
What error does the following code raise and why?
NumPy
import numpy as np
arr = np.array([[1, 2], [3, 4], [5, 6]])
print(arr[[0, 2], 1, 0])
AIndexError: too many indices for array
BTypeError: unhashable type: 'list'
CValueError: shape mismatch
DNo error, prints [2 6]
Attempts:
2 left
💡 Hint
Check how many indices are used for a 2D array.
🚀 Application
advanced
2:00remaining
Selecting rows with multiple conditions using indexing
Which code correctly selects rows from the array where the first column is > 2 and the second column is < 5?
NumPy
import numpy as np
arr = np.array([[1, 4], [3, 2], [5, 6], [4, 3]])
Aarr[arr[:, 0] > 2, arr[:, 1] < 5]
Barr[arr[:, 0] > 2 and arr[:, 1] < 5]
Carr[(arr[:, 0] > 2) & (arr[:, 1] < 5)]
Darr[(arr[:, 0] > 2) | (arr[:, 1] < 5)]
Attempts:
2 left
💡 Hint
Use bitwise operators (&, |) for element-wise logical operations in NumPy.
🧠 Conceptual
expert
2:30remaining
Why does modifying a slice affect the original array but modifying a fancy index does not?
Choose the best explanation for why modifying a slice of a NumPy array changes the original array, but modifying a fancy indexed array does not.
ASlices create copies of the data; fancy indexing returns views that share memory.
BSlices return views that share memory with the original array; fancy indexing returns a copy with separate memory.
CBoth slices and fancy indexing return copies, but slices are linked to the original array by reference.
DFancy indexing modifies the original array only if the array is 1D; slices always modify the original.
Attempts:
2 left
💡 Hint
Think about memory sharing between the original array and the indexed result.