Predict the output
What does this print?
def middle(vals: list[int]) -> int:
return vals[len(vals) // 2]
for case in ([3, 1, 2], [5], []):
try:
print(middle(case))
except IndexError:
print("IndexError on", case)Choose an answer, then open Show answer below to check it.
Show answer
Answer: A 1 5 IndexError on []
Right: the empty case is the one that breaks, which is why it belongs in every test list.
Edge cases such as empty input often fail where the main example passes, so they are worth naming before you finish.
Why not the others?
- B 1 5 0. Indexing an empty list raises IndexError.
- C 2 5 IndexError on []. The middle position of [3, 1, 2] holds 1; this function does not sort.