0
0
NumPydata~20 mins

Combining fancy and slice indexing in NumPy - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Fancy Slice Indexing Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of combining fancy and slice indexing on a 2D array
What is the output of this code snippet?
import numpy as np
arr = np.arange(16).reshape(4,4)
result = arr[[1,3], 1:3]
NumPy
import numpy as np
arr = np.arange(16).reshape(4,4)
result = arr[[1,3], 1:3]
print(result)
A
[[1 2]
 [9 10]]
B
[[1 2 3]
 [9 10 11]]
C
[[5 6 7]
 [13 14 15]]
D
[[5 6]
 [13 14]]
Attempts:
2 left
💡 Hint
Remember that fancy indexing selects specific rows, and slice indexing selects columns.
data_output
intermediate
2:00remaining
Shape of array after combining fancy and slice indexing
Given the code below, what is the shape of the resulting array?
import numpy as np
arr = np.arange(27).reshape(3,3,3)
result = arr[[0,2], :, 1:3]
NumPy
import numpy as np
arr = np.arange(27).reshape(3,3,3)
result = arr[[0,2], :, 1:3]
print(result.shape)
A(2, 3, 2)
B(3, 2, 2)
C(2, 2, 3)
D(3, 3, 2)
Attempts:
2 left
💡 Hint
Fancy indexing on the first axis selects 2 slices, then full slice on second axis, then slice on third axis.
🔧 Debug
advanced
2:00remaining
Identify the error in combining fancy and slice indexing
What error does this code raise?
import numpy as np
arr = np.arange(9).reshape(3,3)
result = arr[1:3, [0, 2], 1]
NumPy
import numpy as np
arr = np.arange(9).reshape(3,3)
result = arr[1:3, [0, 2], 1]
ATypeError: unhashable type: 'slice'
BIndexError: too many indices for array
CValueError: shape mismatch in fancy indexing
DNo error, outputs a 2D array
Attempts:
2 left
💡 Hint
Check how many indices the array has and how many are used.
🚀 Application
advanced
2:00remaining
Extract specific rows and columns using combined indexing
You have a 5x5 numpy array. You want to extract rows 0, 2, and 4, but only columns 1 to 3 (inclusive start, exclusive end). Which code snippet correctly does this?
Aarr[1:4, 0:3]
Barr[1:4, [0, 2, 4]]
Carr[[0, 2, 4], 1:4]
Darr[[1, 2, 3], 0:3]
Attempts:
2 left
💡 Hint
Remember fancy indexing selects rows, slice selects columns.
🧠 Conceptual
expert
2:00remaining
Understanding the output shape when combining fancy and slice indexing
Consider a 3D numpy array with shape (4, 5, 6). If you use fancy indexing on the first axis with 2 indices and slice indexing on the second axis with 3:5, and slice indexing on the third axis with 1:4, what will be the shape of the resulting array?
A(2, 2, 3)
B(4, 2, 3)
C(2, 3, 3)
D(2, 5, 3)
Attempts:
2 left
💡 Hint
Fancy indexing changes the size of the first axis to the number of indices selected.