Sub topic 7
How fast is lookup? Comparing the four types
This chapter assumes you can write Python loops and functions and know the basics of lists, tuples, dicts, and sets from the earlier chapters. You should also know that dict keys and set elements must be hashable.
The working model
Lookup cost depends on how the collection stores its data.
- A list and a tuple store items in order, one after another. To ask "is this value in here?", Python compares the value with each item until it finds a match or reaches the end. The cost grows with the length, which is written O(n).
- A dict and a set use a hash table. Python computes the hash of the key, which is an integer, and uses it to jump to the place where the key would be stored. The cost stays roughly the same however large the collection grows. This is written O(1) on average.
Position-based access is a different question. items[i] on a list or tuple is O(1), because Python goes straight to slot i. The slow operation is searching by value.
| Operation | list | tuple | dict | set |
|---|---|---|---|---|
| Access by index | O(1) | O(1) | not available | not available |
| `x in collection` | O(n) | O(n) | O(1) average (checks keys) | O(1) average |
| Look up by key | not available | not available | O(1) average | not available |
| Add one item | O(1) amortized (`append`) | not possible | O(1) average | O(1) average |
| Remove a given value | O(n) | not possible | O(1) average (`del d[k]`) | O(1) average |
"Amortized" means that an occasional append is slow because the list must grow, but the average over many appends is constant. "Average" for hash tables means that rare hash collisions can slow a single operation, but typical use is constant.
Measuring the difference
Do not trust the table alone. Measure it with timeit, which is in the standard library. This script searches for the last item, which is the worst case for a list.
import timeit
for n in (1_000, 10_000, 100_000):
data_list = list(range(n))
data_set = set(data_list)
target = n - 1
list_time = timeit.timeit(lambda: target in data_list, number=1_000)
set_time = timeit.timeit(lambda: target in data_set, number=1_000)
print(f"n={n:>7} list: {list_time:.5f}s set: {set_time:.5f}s")On a typical machine, the list time grows about tenfold each time n grows tenfold. The set time stays nearly flat. Exact numbers vary by machine, so compare the trend and not the values.
Where this matters: repeated membership tests
The common mistake is testing membership against a list inside a loop. Each test is O(n), so the whole loop is O(n × m).
allowed_list = list(range(50_000))
requests = [49_999, 12, 7, 49_998] * 2_500
# Slow: every `in` scans the list
count_slow = sum(1 for r in requests if r in allowed_list)
# Fast: build the set once, then each `in` is a hash lookup
allowed_set = set(allowed_list)
count_fast = sum(1 for r in requests if r in allowed_set)
print(count_slow == count_fast) # TrueBuilding the set costs O(n) once. After that, every test is cheap. If you test only once or twice, building the set is not worth it.
Dicts versus searching a list of pairs
The same idea applies to lookup by key. If you store records as a list of tuples, finding one means scanning.
pairs = [("ana", 31), ("ben", 27), ("cy", 45)]
def age_from_pairs(name):
for key, value in pairs:
if key == name:
return value
return None
ages = dict(pairs)
print(age_from_pairs("cy")) # 45, found by scanning
print(ages.get("cy")) # 45, found by hashingWith three records the difference is invisible. With a million, the dict is far faster.
Common errors
- Using
inon a list inside a loop when a set would do. Convert once, outside the loop. - Forgetting that
inon a dict checks keys, not values.31 in agesisFalse.31 in ages.values()scans the values and is O(n). - Assuming a set is always better. A set uses more memory than a list, and it loses order and duplicates. For small collections, around a few dozen items, a list can be as fast or faster, because hashing has its own overhead.
- Converting inside the loop. Writing
if r in set(allowed_list)rebuilds the set on every iteration, which is slower than the list scan. - Using unhashable items. A set of lists fails with
TypeError. Use tuples or frozensets as elements.
Exercises
Exercise
A program checks if word in stop_words for each of 2 million words, and stop_words is a list of 500 entries. What single change speeds it up most, and why?
Show answer
Convert stop_words to a set once, before the loop, with stop_words = set(stop_words). Each list test scans up to 500 entries, while each set test is an average O(1) hash lookup. The one-time conversion costs only about 500 steps.
Exercise
Given ages = {"ana": 31, "ben": 27}, what do "ana" in ages and 31 in ages return, and which one is O(1)?
Show answer
"ana" in ages returns True and 31 in ages returns False. Both checks are O(1) on average, because in on a dict tests keys by hashing. To test for a value you must use 31 in ages.values(), which scans and is O(n).