Sub topic 7
How fast is lookup? Comparing the four types
This chapter assumes you know what mutability and hashability mean, and that you can write loops, comprehensions, and functions. You should also be able to run a short script and read its printed output. The goal is a working model of what x in container and container[key] cost for lists, tuples, dicts, and sets, plus the habits that follow from it.
Why cost matters
Two pieces of code can return the same answer while one takes a millisecond and the other takes a minute. The difference often comes from how a lookup is carried out. Programmers describe this with Big-O notation, which says how the work grows as the collection grows.
- O(1) means constant time. The work does not depend on the collection's size.
- O(n) means linear time. Doubling the collection roughly doubles the work.
- O(log n) means the work grows slowly. Doubling the collection adds one step.
Two qualifiers matter for Python's collections. "Average case" means typical inputs. "Amortized" means that a few operations are expensive, but the cost averaged over many operations is low.
Big-O ignores constant factors. It tells you how a cost scales, not which option is faster for 10 items.
How a list or tuple finds something
A list stores references to its items in a contiguous array. That layout makes access by position cheap, because Python computes the memory location from the index. items[5000] costs the same as items[0].
Searching by value is different. The list has no index of values, so x in items must compare x with each item from the start until it finds a match or runs out of items.
items = [4, 8, 15, 16, 23, 42]
print(items[3]) # 16, constant time: jump straight to position 3
print(23 in items) # True, found after 5 comparisons
print(99 in items) # False, needed all 6 comparisons
print(items.index(42)) # 5, also a linear scanA tuple behaves the same way. It is also an array of references, so indexing is O(1) and membership is O(n). Being immutable does not make a tuple faster to search. It only means the tuple cannot change after creation.
Each comparison checks identity first (is) and then equality (==). The cost per comparison therefore depends on the items. Comparing small integers is cheap. Comparing long strings or large nested objects is more expensive.
Searching is cheapest when the item is near the front. Python stops at the first match, so the worst case is a missing item, which costs a full scan.
How a dict or set finds something
A dict and a set are both hash tables. When you look up x, Python does this:
- It calls
hash(x)to get an integer. - It uses that integer to choose a starting slot in an internal table.
- If the slot is empty,
xis not present. - If the slot holds an object with the same hash that is identical or equal to
x, the lookup succeeds. - If the slot holds something else, Python probes another slot and repeats from step 3.
Python keeps the table sparse. It resizes the table as it fills, so most slots are empty or hold the right key and probe sequences stay short. The lookup does not look at the other items, so its cost does not grow with the number of items.
This is why dict keys and set elements must be hashable. The hash is computed when you insert, and it must give the same answer when you look up. If a key could change its hash while stored, the lookup would go to the wrong slot.
Equal objects must hash equally
The table design relies on one rule: if a == b, then hash(a) == hash(b). Python's built-in types follow it. Numbers show a visible case:
print(1 == 1.0, hash(1) == hash(1.0)) # True True
table = {1: "int key"}
print(table[1.0]) # int key
print(True in {1, 2}) # True, because True == 1When you define your own class with __eq__, you must define a matching __hash__. If you do not, Python sets __hash__ to None and instances become unhashable.
Summary of costs
The table lists typical costs for the common operations. "Average" for dict and set refers to the hash-table behavior described above.
| Operation | list | tuple | dict | set |
|---|---|---|---|---|
| Access by position `c[i]` | O(1) | O(1) | not supported | not supported |
| Access by key `c[k]` | not supported | not supported | O(1) average | not supported |
| Membership `x in c` | O(n) | O(n) | O(1) average (keys) | O(1) average |
| Add one item | O(1) amortized (`append`) | not supported | O(1) average | O(1) average |
| Insert or remove at the front | O(n) | not supported | not applicable | not applicable |
| Remove by value or key | O(n) (`remove`) | not supported | O(1) average | O(1) average |
| Iterate all items | O(n) | O(n) | O(n) | O(n) |
| Build from n items | O(n) | O(n) | O(n) average | O(n) average |
Two entries need explanation.
appendis amortized O(1). A list reserves extra capacity. Most appends fill spare room. Occasionally the list must grow and copy its array, which costs O(n), but those copies are rare enough that the average stays constant.- Front insertion is O(n).
insert(0, x)andpop(0)shift every other item by one position. If you need to add or remove at both ends, thecollections.dequetype covers that case. It is introduced in the last chapter of this tutorial.
Measuring the difference
Measure when you are unsure. The timeit module runs a snippet many times and reports total seconds. The following script times a missing-item lookup, which is the worst case for the list.
import timeit
n = 100_000
data_list = list(range(n))
data_set = set(data_list)
data_dict = dict.fromkeys(data_list)
missing = -1 # not present, so the list must scan every item
for name, container in [("list", data_list), ("set", data_set), ("dict", data_dict)]:
runs = 1000
total = timeit.timeit(lambda: missing in container, number=runs)
print(f"{name:5} {total / runs * 1e6:10.2f} microseconds per lookup")Exact numbers vary by machine. On a typical laptop the list takes on the order of a millisecond per lookup and the set and dict take a fraction of a microsecond, a gap of several thousand times. Run the script again with n = 1_000_000 and you should see the list time grow about tenfold while the set and dict times barely change.
The most common practical win: convert before looping
Membership tests inside a loop multiply their cost. If you test each of m items against a list of n items, the work is O(m × n). Converting the list to a set once costs O(n), and each test then costs O(1) on average.
def common_slow(a, b):
return [x for x in a if x in b] # scans list b for every x
def common_fast(a, b):
b_set = set(b) # build once
return [x for x in a if x in b_set] # constant-time test
first = [5, 3, 9, 3, 7]
second = [7, 3, 11]
print(common_slow(first, second)) # [3, 3, 7]
print(common_fast(first, second)) # [3, 3, 7]Both functions return the same result and keep the order and duplicates of a. Only the second one scales. If you do not need the order or duplicates, set(a) & set(b) is even shorter.
The conversion is not free. Building the set costs O(n) time and extra memory, because a hash table uses more space than a list of the same items. If you test membership once, a plain scan is cheaper than building a set. Convert when you test many times against the same collection.
Edge cases and gotchas
`in` on a dict checks keys only
k in some_dict is a hash lookup on the keys. v in some_dict.values() is a linear scan, because values are not hashed into a table.
ages = {"ana": 31, "ben": 27}
print("ana" in ages) # True, O(1) average
print(31 in ages.values()) # True, O(n): scans every valueIf you often need to find a key from a value, keep a second dict that maps values back to keys. This only works if the values are unique and hashable.
Hash computation has a cost too
Hashing an int is cheap. Hashing a string is proportional to its length, although Python caches the hash inside the string object after the first call. Hashing a tuple means hashing every element, and the result is not cached. A lookup with a long tuple as the key is therefore O(1) in the size of the dict but still O(k) in the length k of the key. The same applies to frozensets used as keys.
Worst case is O(n)
If many keys share the same hash, the probe sequence grows long and each lookup compares against many entries. Built-in types are designed to avoid this, and string hashing is randomized per process to resist crafted inputs. A bad __hash__ in your own class can still cause it:
import time
class BadKey:
def __init__(self, value):
self.value = value
def __hash__(self):
return 1 # every instance collides
def __eq__(self, other):
return isinstance(other, BadKey) and self.value == other.value
class GoodKey(BadKey):
def __hash__(self):
return hash(self.value)
def build(cls, n):
start = time.perf_counter()
table = {cls(i): i for i in range(n)}
return time.perf_counter() - start
print(f"bad hash : {build(BadKey, 1500):.3f} s")
print(f"good hash: {build(GoodKey, 1500):.3f} s")The first line is much slower, and the gap grows quadratically as you raise the count. The lesson is to derive __hash__ from the same fields that __eq__ compares.
Small collections are different
For a handful of items, a list or tuple scan can beat a set lookup. Hashing has a fixed overhead, and a scan of five items is a few fast comparisons. Do not convert a three-item list to a set for speed. Choose a list or tuple for small fixed groups such as if mode in ("r", "w", "a"), where the readability is also good.
Sorted lists give O(log n) search
If you need a collection that stays ordered and you rarely modify it, a sorted list with binary search is an option between a scan and a hash table. The bisect module does the search.
from bisect import bisect_left
def contains_sorted(sorted_items, x):
i = bisect_left(sorted_items, x)
return i < len(sorted_items) and sorted_items[i] == x
nums = [2, 5, 8, 13, 21, 34]
print(contains_sorted(nums, 13)) # True
print(contains_sorted(nums, 14)) # FalseThis costs O(log n) per search and works with items that can be ordered but are not hashable. Inserting into the sorted list still costs O(n), so it suits read-heavy data.
Iteration order and speed are separate questions
All four types iterate in O(n). Dicts keep insertion order, and sets do not promise any order. Hash-based speed does not give you sorted output. Use sorted(the_set) when you need a predictable order, which costs O(n log n).
Quick rules from the cost model
- Looking things up by key or testing membership many times: use a dict or set.
- Reading by position or iterating in order: a list or tuple is fine, and indexing is O(1).
- Searching a list inside a loop is a signal to convert it to a set first.
- Never rely on cost alone. If the collection is small or you search once, choose for clarity.
- Measure with
timeitwhen the choice matters, and use realistic sizes.
Exercise
A function receives a list blocked containing 50,000 user ids and a list requests containing 200,000 ids. It does [r for r in requests if r not in blocked]. Roughly how many comparisons can this need in the worst case, and what one change reduces the cost? Write the changed line.
Show answer
Each r not in blocked can scan all 50,000 items, so the worst case is about 200,000 × 50,000 = 10 billion comparisons. Convert blocked to a set once, which costs about 50,000 operations, and each membership test then costs O(1) on average: blocked_set = set(blocked) followed by [r for r in requests if r not in blocked_set]. The total is then roughly 250,000 operations.
Exercise
Why is 31 in ages.values() slow for a dict named ages, while "ana" in ages is fast?
Show answer
"ana" in ages hashes the key and jumps to its slot in the hash table, so the cost does not depend on the dict size. A dict hashes only its keys, not its values, so 31 in ages.values() has to compare 31 with each value in turn, which is O(n).