0
0
NumPydata~10 mins

Slicing rows and columns in NumPy - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to select the first three rows of the array.

NumPy
import numpy as np
arr = np.array([[1, 2], [3, 4], [5, 6], [7, 8]])
result = arr[1]
Drag options to blanks, or click blank then click option'
A[:3]
B[3:]
C[1:3]
D[:4]
Attempts:
3 left
💡 Hint
Common Mistakes
Using [3:] which selects rows starting from index 3, not the first three rows.
Using [:4] which selects four rows but the array only has four rows total.
Using [1:3] which selects rows 1 and 2, not the first three rows.
2fill in blank
medium

Complete the code to select the second column from all rows.

NumPy
import numpy as np
arr = np.array([[10, 20, 30], [40, 50, 60], [70, 80, 90]])
col = arr[1]
Drag options to blanks, or click blank then click option'
A[1, :]
B[:, 1]
C[:, 2]
D[1, 1]
Attempts:
3 left
💡 Hint
Common Mistakes
Using [1, :] which selects the second row, not the second column.
Using [:, 2] which selects the third column, not the second.
Using [1, 1] which selects a single element, not a column.
3fill in blank
hard

Fix the error in the code to select rows 1 and 2 and columns 0 and 1.

NumPy
import numpy as np
arr = np.array([[5, 6, 7], [8, 9, 10], [11, 12, 13]])
subset = arr[1]
Drag options to blanks, or click blank then click option'
A[0:2, 1:3]
B[1:2, 0:1]
C[1:3, 0:2]
D[1, 2, 0, 1]
Attempts:
3 left
💡 Hint
Common Mistakes
Using [1:2, 0:1] which selects only row 1 and column 0.
Using [0:2, 1:3] which selects wrong rows and columns.
Using [1, 2, 0, 1] which is invalid syntax for slicing.
4fill in blank
hard

Fill both blanks to create a dictionary with words as keys and their lengths if length is greater than 3.

NumPy
words = ['apple', 'bat', 'carrot', 'dog']
lengths = {word: [1] for word in words if [2]
Drag options to blanks, or click blank then click option'
Alen(word)
Blen(word) > 3
Cword
Dword > 3
Attempts:
3 left
💡 Hint
Common Mistakes
Using word instead of len(word) for the value.
Using word > 3 which compares string to number and causes error.
Using len(word) without a condition, which includes all words.
5fill in blank
hard

Fill all three blanks to create a dictionary with uppercase words as keys, their lengths as values, only if length is greater than 3.

NumPy
words = ['tree', 'cat', 'house', 'dog']
result = [1]: [2] for w in words if [3]
Drag options to blanks, or click blank then click option'
Aw.upper()
Blen(w)
Clen(w) > 3
Dw.lower()
Attempts:
3 left
💡 Hint
Common Mistakes
Using w.lower() instead of w.upper() for keys.
Using w instead of len(w) for values.
Using wrong condition like w > 3 which causes error.