Sub topic 2
Fast membership tests and removing duplicates
This chapter assumes you can write Python loops and functions, know how lists and indexing work, and have a basic idea of Big-O notation. Hash internals come in later chapters. Here you use sets as a tool.
Why a list is slow for membership
The in operator on a list compares your value to each element until it finds a match. For a list of n items, that is O(n) work. A set stores items so that in jumps close to the right spot. On average that takes constant time, written O(1), no matter how many items the set holds.
A set is an unordered collection of unique, hashable values. "Hashable" means Python can compute an integer from the value. Strings, numbers and tuples of those are hashable.
Removing duplicates
Passing any iterable to set() keeps one copy of each value. The in operator then answers membership questions quickly.
emails = ["[email protected]", "[email protected]", "[email protected]"]
unique = set(emails)
print(len(unique)) # 2
print("[email protected]" in unique) # TrueKeeping the original order
set(emails) loses the order of the input. If you need the first occurrence of each value, in order, track what you have seen in a set and build a list alongside it.
def dedupe_in_order(items):
seen = set()
result = []
for item in items:
if item not in seen:
seen.add(item)
result.append(item)
return result
print(dedupe_in_order(["b", "a", "b", "c", "a"])) # ['b', 'a', 'c']This runs in O(n) overall. The version that checks if item not in result on a list is O(n²), because each check scans the growing list.
Filtering against a large collection
A common job is to check many values against a fixed collection. Build the set once, outside the loop.
blocked = {"[email protected]", "[email protected]"}
incoming = ["[email protected]", "[email protected]", "[email protected]"]
allowed = [e for e in incoming if e not in blocked]
print(allowed) # ['[email protected]', '[email protected]']When a set is not worth it
Building a set costs O(n) time and extra memory. If you test membership once on a small list, in on the list is simpler and just as fast. A set pays off when you test many times, or when the collection is large.
| Situation | Better choice |
|---|---|
| Many membership tests on a large collection | set |
| One test on a short list | list |
| Need duplicates or positions preserved | list |
| Need unique values in first-seen order | set plus list, as above |
Common errors
- Putting unhashable values in a set.
{[1, 2]}raisesTypeError: unhashable type: 'list'. Convert to a tuple first:{(1, 2)}. - Writing
{}for an empty set. That creates an empty dict. Useset(). - Relying on the printed order of a set. Treat it as arbitrary.
Exercise
A function receives a list of 100,000 user IDs and a list of 50,000 banned IDs. It returns the user IDs that are not banned, keeping their original order and duplicates. Write the body in a way that avoids O(n·m) work.
Show answer
Build a set of the banned IDs once, then filter with a list comprehension: banned_set = set(banned) and return [u for u in users if u not in banned_set]. Each check is O(1) on average, so the total is O(n + m). The list comprehension preserves order and duplicates.
Exercise
Why does dedupe_in_order keep both a set and a list instead of only a list?
Show answer
The set gives O(1) average membership checks, and the list keeps the first-seen order. Using only the list would make each in check O(n) and the whole function O(n²).