Predict the output
Which container answers this faster? What does this print?
import timeit
xs = list(range(100_000))
ss = set(xs)
t_list = timeit.timeit(lambda: 99_999 in xs, number=50)
t_set = timeit.timeit(lambda: 99_999 in ss, number=50)
print(t_set < t_list)Choose an answer, then open Show answer below to check it.
Show answer
Answer: A True
Right: the set checks one bucket; the list scans 100,000 items.
A hash lookup does constant work, while the list has to compare against every earlier item first.
Why not the others?
- B False. List membership is a linear scan, so it is far slower for an item at the end.
- C It depends on the item's value. For an item near the end of the list, the scan is always long.