Performance: When to Use Sets
Concepts covered: Sets, List Search
x in collection reads the same for a list and a set, but the 2 do different work. A list walks its elements from index 0 and compares each with == until one matches or the list ends, so a miss costs 1 comparison per element. A set computes hash(x) and uses it to jump to 1 slot of its hash table. It calls == only on entries whose stored hash equals hash(x). Counting the == calls against 10,000 ids makes the difference visible.
class UserId:
eq_calls = 0
def __init__(self, v):
self.v = v
def __eq__(self, other):
UserId.eq_calls += 1
return self.v == other.v
def __hash__(self):
return hash(self.v)
known_list = [UserId(i) for i in range(10000)]
known_set = set(known_list)
for probe in (UserId(9999), UserId(-1)):
UserId.eq_calls = 0
in_list = probe in known_list
list_calls = UserId.eq_calls
UserId.eq_calls = 0
in_set = probe in known_set
print(probe.v, in_list, list_calls, in_set, UserId.eq_calls)Output:
9999 True 10000 True 1 -1 False 10000 False 0
Both collections hold the same 10,000 objects. The list made 10,000 comparisons for the hit, which sat at the end, and 10,000 more for the miss. The set made 1 comparison for the hit, to confirm the match, and 0 for the miss: no stored hash equalled the probe's, so there was nothing to compare. This is what O(n) against O(1) average means in practice. The list's cost grows with its length, and the set's stays flat whether it holds 10 ids or 10 million.
The number, worked out
A nightly job flags test traffic by checking 500,000 order events against 20,000 test-account ids. Nearly every event is real, so nearly every check is a miss, and a miss against a list scans all 20,000 ids. That comes to 500,000 times 20,000, or 10 billion comparisons, where a set needs 500,000 hash lookups. On typical hardware, the same filter takes roughly:
- ~2 min
- ~0.1 s
The gap holds across the operations pipelines use most:
| Operation | list | set |
|---|---|---|
| x in c | O(n), scans until a match | O(1) average, 1 hash lookup |
| Add 1 element | O(1) amortised append | O(1) average add |
| Remove by value | O(n), find then shift the tail | O(1) average |
| Common elements of a and b | O(len(a) x len(b)) with nested in | O(min(len(a), len(b))) via a & b |
| Keeps order and duplicates | Yes | No |
Comparing 2 extracts is the case most often missed. Finding the customer ids present in both of 2 lists of 100,000 ids with a nested in takes up to 10 billion comparisons. set(a) & set(b) hashes each side once and then probes from the smaller set.
The O(1) is an average. If many elements share a hash, lookups degrade toward O(n), which is one reason CPython salts string hashing with a random seed at startup.
When a list is still the right call
- Building costs O(n): set(ids) hashes every id, so for a single lookup a list scan is cheaper.
- Memory: in CPython 3.9, set(range(10000)) takes about 524 KB and list(range(10000)) about 80 KB.
- Order and duplicates: rows, ranked results and repeated payments need a list.
- Unhashable elements: a collection of dicts or lists cannot be stored in a set at all.
- Tiny fixed collections: for 3 or 4 items, a scan costs about what hashing does, so readability decides.
Set for membership, list for order
Most pipelines need both behaviours: drop repeated ids, and emit the survivors in arrival order. The standard pattern keeps a seen set for the O(1) check and a list for the output. Each structure is used only for the job it does well.
events = [8814, 1203, 8814, 5521, 1203, 7740]
seen = set()
unique = []
for user_id in events:
if user_id not in seen:
seen.add(user_id)
unique.append(user_id)
print(unique)[8814, 1203, 5521, 7740]
Each id costs 1 hash lookup against seen. A list in that role would rescan the growing output on every event, which brings back the quadratic cost on a long stream.
The most common performance bug with sets puts the right structure in the wrong place.
A filter takes minutes on 500,000 events. Its loop body is if e["account_id"] in set(test_ids): flagged.append(e), where test_ids is a list of 20,000 ids. Which change fixes it?
- Build test_set = set(test_ids) once before the loop and test against test_set.
- Test against test_ids directly, since a list needs no building.
- Sort test_ids first so in can stop early.
- Convert events to a set so each event is visited once.
About this lesson
This section is part of the Sets: Advanced lesson on DataDriven, the home of data engineering. Lessons cover SQL, Python, Spark, data modeling and pipeline architecture, and each section pairs its explanation with worked examples and practice you run as you go.