Tip: Choose Save as PDF in the print dialog to download. Use A4 paper size.
Shade in the A or B circle for each question.
Draw a line connecting each item on the left to its match on the right.
| Left column | Right column | |
|---|---|---|
| 1items[len(items)] | Aif 0 <= i < len(items): print(items[i]) | |
| 2items[len(items) - 1] | Bitems = [] print(items[0]) | |
| 3Prevent an IndexError with a range check before using the index | CGets the last item in the list safely, as long as the list is not empty | |
| 4Accessing the first item of an empty list causes an IndexError | DRaises an IndexError, because the last valid index is len(items) - 1 | |
| 5for i in range(len(items) + 1): print(items[i]) | EA 3-item list only has indexes 0, 1 and 2, so index 3 is out of range. The last item is scores[2] or scores[-1]. | |
| 6scores = [70, 85, 90] print(scores[3]) | FOff-by-one error: the loop goes one step too far, so the last value of i equals len(items) and raises an IndexError. Use range(len(items)). |
Complete each line of code by filling in the missing parts.
Shade in the letter of the line that contains an error.
IndexError — A runtime error raised when code uses an index that is not in the list, such as items[5] in a 5-item list. The last valid index is len(items) - 1.items = [4, 8, 15, 16, 23]
last = items[len(items) - 1]
print(last)items = ["a", "b", "c"]
for i in range(len(items)):
print(items[i])items = []
if len(items) > 0:
print(items[0])try:
print(items[5])
except IndexError:if index >= 0 and index < len(items):
print(items[index])