Sub topic 10
Practical uses: deduplication and fast lookups
This chapter assumes you know how to create sets, that elements must be hashable, how in works on a set, and the union, intersection and difference operators. Here you apply them to two everyday jobs: removing duplicates and checking membership quickly.
Removing duplicates
The shortest way to drop duplicates is to pass an iterable to set(). Each element is stored once.
emails = ["[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]"]
unique = set(emails)
print(len(unique)) # 3A set has no defined order, so list(set(emails)) can return the items in a different order than they appeared. If order matters, use dict.fromkeys. Dictionary keys are unique and keep insertion order, so the first occurrence of each item wins.
items = ["b", "a", "b", "c", "a"]
print(len(set(items))) # 3, order not guaranteed
print(list(dict.fromkeys(items))) # ['b', 'a', 'c'], first-seen orderBoth approaches need hashable elements. A list of lists fails with TypeError: unhashable type: 'list'. Convert each inner list to a tuple first, then deduplicate.
rows = [[1, 2], [3, 4], [1, 2]]
unique_rows = {tuple(r) for r in rows}
print(sorted(unique_rows)) # [(1, 2), (3, 4)]Fast lookups
Testing x in some_list scans the list from the start, so the time grows with the list length. Testing x in some_set computes a hash and jumps to the right slot, which takes roughly constant time on average. The difference matters when you test many items against a large collection.
allowed_list = [f"user{i}" for i in range(100_000)]
allowed_set = set(allowed_list)
requests = ["user99999", "user5", "nobody"]
print([r in allowed_set for r in requests]) # [True, True, False]Both versions give the same answers. The set version avoids scanning up to 100,000 entries per request. Building the set costs time once, so it pays off when you do repeated lookups, not a single one.
Combining set algebra with real data
Set operators express many data questions directly. Suppose you have the users who logged in this week and last week.
last_week = {"ana", "ben", "cy", "dee"}
this_week = {"ben", "cy", "eli"}
print(sorted(this_week - last_week)) # ['eli'], new users
print(sorted(last_week - this_week)) # ['ana', 'dee'], users who left
print(sorted(this_week & last_week)) # ['ben', 'cy'], returning users
print(sorted(this_week | last_week)) # all users seen in either weekEach line replaces a loop with an if test. The code reads like the question you are asking.
Filtering with a lookup set
A common pattern is to keep a set of values to exclude or include, then filter another sequence with it.
stop_words = {"the", "a", "of", "and"}
text = "the history of the art and a science"
words = [w for w in text.split() if w not in stop_words]
print(words) # ['history', 'art', 'science']Use a set for stop_words even when it is small. It documents intent and stays fast if the list grows.
Finding duplicates
To find which items repeat, track what you have seen in a set.
def find_duplicates(values):
seen = set()
dupes = set()
for v in values:
if v in seen:
dupes.add(v)
else:
seen.add(v)
return dupes
print(sorted(find_duplicates([1, 2, 3, 2, 4, 1]))) # [1, 2]This makes one pass over the data. Comparing every item with every other item would take time proportional to the square of the length.
Choosing the right tool
| Need | Use | Column |
|---|---|---|
| Unique items, order irrelevant | `set(items)` | |
| Unique items, keep first-seen order | `list(dict.fromkeys(items))` | |
| Many membership tests | Build a set once | |
| One membership test on a list | `x in the_list` | |
| Compare two groups | `&`, ` | `, `-`, `^` |
Exercise
You have names = ["Zoe", "Al", "Zoe", "Bo", "Al"]. Write one expression that returns the unique names in first-seen order. Then explain why list(set(names)) is not a safe replacement when order matters.
Show answer
list(dict.fromkeys(names)) returns ['Zoe', 'Al', 'Bo']. A set has no guaranteed order, so list(set(names)) may list the names in any order.
Exercise
A program checks 50,000 IDs against a list of 200,000 valid IDs using in on the list. How can you speed it up, and why does it help?
Show answer
Convert the valid IDs to a set once with valid = set(valid_ids) and test id in valid. Each set lookup takes roughly constant time on average, while each list lookup scans the list, so the total work drops sharply.