0
0
NumPydata~10 mins

Negative indexing 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 last element of the numpy array.

NumPy
import numpy as np
arr = np.array([10, 20, 30, 40, 50])
last_element = arr[1]
Drag options to blanks, or click blank then click option'
A[0]
B[1]
C[-1]
D[-5]
Attempts:
3 left
💡 Hint
Common Mistakes
Using positive index 1 instead of -1.
Using 0 which selects the first element.
Using -5 which selects the first element but is less clear.
2fill in blank
medium

Complete the code to select the second last element of the numpy array.

NumPy
import numpy as np
arr = np.array([5, 15, 25, 35, 45])
second_last = arr[1]
Drag options to blanks, or click blank then click option'
A[-2]
B[1]
C[-1]
D[2]
Attempts:
3 left
💡 Hint
Common Mistakes
Using positive index 2 which selects the third element.
Using -1 which selects the last element.
Using positive index 1 which selects the second element.
3fill in blank
hard

Fix the error in the code to correctly select the last three elements using negative indexing.

NumPy
import numpy as np
arr = np.array([2, 4, 6, 8, 10, 12])
last_three = arr[1]
Drag options to blanks, or click blank then click option'
A[-3:]
B[:3]
C[3:]
D[-3]
Attempts:
3 left
💡 Hint
Common Mistakes
Using [:3] which selects first three elements.
Using [3:] which selects elements from index 3 to end but not negative indexing.
Using [-3] which selects only one element.
4fill in blank
hard

Fill both blanks to create a dictionary with words as keys and their last two characters as values.

NumPy
words = ['apple', 'banana', 'cherry']
last_two_chars = {word: word[1] for word in words if len(word) [2] 2}
Drag options to blanks, or click blank then click option'
A[-2:]
B>
C<
D[:2]
Attempts:
3 left
💡 Hint
Common Mistakes
Using [:2] which gets first two characters.
Using length less than 2 which excludes longer words.
Using negative index without colon which selects single character.
5fill in blank
hard

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

NumPy
words = ['dog', 'elephant', 'cat', 'giraffe']
result = {word[1]: word[2] for word in words if len(word) [3] 3}
Drag options to blanks, or click blank then click option'
A.upper()
B[-1]
C>
D[:1]
Attempts:
3 left
💡 Hint
Common Mistakes
Using [:1] which gets first character instead of last.
Using length less than or equal to 3 which includes short words.
Not converting keys to uppercase.