0
0
Data Analysis Pythondata~20 mins

Array indexing and slicing in Data Analysis Python - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Array Slicing Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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)
A
[[50 60]
 [80 90]]
B
[[40 50]
 [70 80]]
C
[[20 30]
 [50 60]]
D
[[40 60]
 [70 90]]
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).
data_output
intermediate
1: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))
A3
B4
C2
D5
Attempts:
2 left
💡 Hint
Remember slicing includes the start index but excludes the end index.
🔧 Debug
advanced
2: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)
ASyntaxError: invalid syntax
BTypeError: unhashable type: 'slice'
CIndexError: too many indices for array
DNo error, outputs [1 3 5]
Attempts:
2 left
💡 Hint
Check how many dimensions the array has and how many indices are used.
🧠 Conceptual
advanced
2: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)
A[50 40 30 20]
B[40 30 20]
C[10 20 30]
D[50 40 30]
Attempts:
2 left
💡 Hint
Negative step means slicing backwards, start index is included, end index is excluded.
🚀 Application
expert
2: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]])
Aarr[range(3), range(3)]
Barr[:, 0]
Carr[0:3, 0:3]
Darr[::2, ::2]
Attempts:
2 left
💡 Hint
Think about how to select elements where row and column indices are the same.