0
0
NumPydata~10 mins

Slicing with start:stop:step 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 slice the array from index 1 to 5 (exclusive).

NumPy
import numpy as np
arr = np.array([10, 20, 30, 40, 50])
sliced = arr[[1]:5]
print(sliced)
Drag options to blanks, or click blank then click option'
A4
B0
C2
D1
Attempts:
3 left
💡 Hint
Common Mistakes
Using 0 as start index which includes the first element.
Using 5 as start index which is out of range.
2fill in blank
medium

Complete the code to slice the array to get every second element from the start to the end.

NumPy
import numpy as np
arr = np.array([5, 10, 15, 20, 25, 30])
sliced = arr[[1]]
print(sliced)
Drag options to blanks, or click blank then click option'
A0:5:2
B1:6:2
C0:6:2
D1:5:2
Attempts:
3 left
💡 Hint
Common Mistakes
Starting at 1 which skips the first element.
Using stop index less than array length causing missing last elements.
3fill in blank
hard

Fix the error in the code to correctly slice the array backwards with step -1.

NumPy
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
sliced = arr[[1]]
print(sliced)
Drag options to blanks, or click blank then click option'
A1::-1
B::-1
C5::-1
D-1::-1
Attempts:
3 left
💡 Hint
Common Mistakes
Using invalid start or stop indices that cause empty slices.
Using positive step with negative indices.
4fill in blank
hard

Fill both blanks to slice the array from index 2 to 8 (exclusive) with step 3.

NumPy
import numpy as np
arr = np.arange(10)
sliced = arr[[1]:[2]:3]
print(sliced)
Drag options to blanks, or click blank then click option'
A2
B7
C8
D9
Attempts:
3 left
💡 Hint
Common Mistakes
Using stop index 7 which excludes index 7 element.
Using step other than 3.
5fill in blank
hard

Fill all three blanks to create a dictionary with words as keys and their lengths as values, only for words longer than 3 letters.

NumPy
words = ['apple', 'bat', 'carrot', 'dog', 'elephant']
lengths = { [1]: [2] for word in words if len(word) [3] 3 }
print(lengths)
Drag options to blanks, or click blank then click option'
Aword
Blen(word)
C>
D{word
Attempts:
3 left
💡 Hint
Common Mistakes
Using square brackets instead of curly braces.
Using wrong comparison operator like '<' instead of '>'.
Not including the condition to filter words.