Challenge - 5 Problems
Array Slicing Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of slicing a 2D NumPy array
What is the output of the following code snippet?
Data Analysis Python
import numpy as np arr = np.array([[10, 20, 30], [40, 50, 60], [70, 80, 90]]) sliced = arr[1:, :2] print(sliced)
Attempts:
2 left
💡 Hint
Remember that arr[1:, :2] means rows from index 1 to end, columns from index 0 up to 2 (not including 2).
✗ Incorrect
The slice arr[1:, :2] selects rows starting from index 1 (second row) to the end, and columns from index 0 up to but not including 2 (first two columns). So it picks rows [[40,50,60],[70,80,90]] and columns [[40,50],[70,80]].
❓ data_output
intermediate1:30remaining
Number of elements after slicing a 1D array
Given the array arr = [5, 10, 15, 20, 25, 30], how many elements are in arr[2:5]?
Data Analysis Python
arr = [5, 10, 15, 20, 25, 30] sliced = arr[2:5] print(len(sliced))
Attempts:
2 left
💡 Hint
Remember slicing includes the start index but excludes the end index.
✗ Incorrect
arr[2:5] includes elements at indices 2, 3, and 4, which are 15, 20, and 25. So the length is 3.
🔧 Debug
advanced2:00remaining
Identify the error in slicing a NumPy array
What error does the following code raise?
Data Analysis Python
import numpy as np arr = np.array([1, 2, 3, 4, 5]) sliced = arr[::2, 1] print(sliced)
Attempts:
2 left
💡 Hint
Check how many dimensions the array has and how many indices are used.
✗ Incorrect
The array arr is 1D, but the code tries to index it with two indices (arr[::2, 1]), which causes an IndexError for too many indices.
🧠 Conceptual
advanced2:00remaining
Effect of negative step in slicing
What is the output of this code?
import numpy as np
arr = np.array([10, 20, 30, 40, 50])
sliced = arr[4:1:-1]
print(sliced)
Attempts:
2 left
💡 Hint
Negative step means slicing backwards, start index is included, end index is excluded.
✗ Incorrect
arr[4:1:-1] starts at index 4 (value 50), goes backwards up to but not including index 1, so it includes indices 4,3,2 which are 50,40,30.
🚀 Application
expert2:30remaining
Extracting a diagonal from a 2D NumPy array using slicing
Given a 3x3 NumPy array, which slicing expression extracts the main diagonal elements as a 1D array?
Data Analysis Python
import numpy as np arr = np.array([[1,2,3],[4,5,6],[7,8,9]])
Attempts:
2 left
💡 Hint
Think about how to select elements where row and column indices are the same.
✗ Incorrect
Using arr[range(3), range(3)] selects elements where row and column indices match: (0,0), (1,1), (2,2), which is the main diagonal.