Sub topic 10
Practical uses: deduplication and fast lookups
Sets are most often used for two jobs: removing duplicates and checking quickly whether a value is present. This chapter shows how to do both in real code, including the cases where a plain set(items) is not enough.
This chapter assumes you know how to create a set, that set elements must be hashable, and how the in operator, the set operators (|, &, -, ^) and comprehensions work. It uses those tools to solve everyday problems.
Deduplication
The one-line version
Passing any iterable to set() drops duplicates, as long as the elements are hashable.
emails = ["[email protected]", "[email protected] ", "[email protected]", "[email protected]"]
raw_unique = set(emails)
print(len(raw_unique)) # 3, because "[email protected]" and "[email protected] " differ
normalized = {e.strip().lower() for e in emails}
print(sorted(normalized)) # ['[email protected]', '[email protected]']Two values are duplicates only if they compare equal. If your data has inconsistent case or stray whitespace, normalize each value before it enters the set. The set comprehension above does this in one step.
A set has no meaningful order. If you need a sorted result, call sorted() on it. If you need the original first-seen order, use one of the techniques below.
Keeping first-seen order
There are two common ways to keep order. For simple hashable values, dict.fromkeys works because dicts preserve insertion order and keys are unique.
items = ["b", "a", "b", "c", "a"]
print(list(dict.fromkeys(items))) # ['b', 'a', 'c']When you need to deduplicate by a derived value, such as case-insensitively, a seen set and a loop is the standard pattern. It keeps the original item but tests the derived key.
def unique(iterable, key=None):
seen = set()
result = []
for item in iterable:
k = item if key is None else key(item)
if k not in seen:
seen.add(k)
result.append(item)
return result
print(unique(["b", "a", "b", "c", "a"]))
# ['b', 'a', 'c']
print(unique(["Apple", "apple", "BANANA", "banana", "cherry"], key=str.lower))
# ['Apple', 'BANANA', 'cherry']The first occurrence wins. Later items whose key was already seen are skipped.
Deduplicating unhashable items
Lists and dicts cannot go in a set. The usual fix is to convert each item to a hashable form for the test, and keep the original item in the output.
rows = [[1, 2], [3, 4], [1, 2]]
# unique() is defined in the previous example
print(unique(rows, key=tuple)) # [[1, 2], [3, 4]]tuple works here because the inner values are numbers. If a row contains nested lists, tuple(row) is still unhashable. In that case you need a recursive conversion, or a serialized form such as json.dumps(row, sort_keys=True).
What counts as a duplicate
Set membership uses hash() and ==. Values that compare equal across types collapse into one element.
print({1, 1.0, True}) # {1}
print(len({0, 0.0, False})) # 1The element that was inserted first stays in the set. This matters if you mix booleans and integers, or integers and floats, in the same collection. Strings and numbers never collapse: "1" and 1 are different.
Floating-point nan is also unusual. float("nan") != float("nan"), but Python's containers check identity before equality. Two references to the same nan object count as one element, while two separately created nan values may not. Avoid nan in sets, or filter it out first.
Fast lookups
Why a set beats a list for membership
Testing x in some_list compares x against elements one by one, so the cost grows with the list length. Testing x in some_set hashes x and jumps to the right slot in a hash table. That takes constant time on average, no matter how large the set is.
import timeit
numbers_list = list(range(100_000))
numbers_set = set(numbers_list)
target = 99_999 # worst case for the list: it is the last element
t_list = timeit.timeit(lambda: target in numbers_list, number=200)
t_set = timeit.timeit(lambda: target in numbers_set, number=200)
print(f"list: {t_list:.4f}s set: {t_set:.6f}s")The exact numbers depend on your machine, but the set is typically thousands of times faster here. Conversion has a cost too. Building the set from the list is a one-time pass over all elements.
| Situation | Better choice | Reason |
|---|---|---|
| Many membership tests against the same collection | Build a set once | Each test is constant time on average |
| One membership test against a list you already have | Use the list | Building the set costs as much as the single scan |
| A handful of items (say, under ten) | Either | The difference is too small to matter |
| You need order, indexing or duplicates | List | Sets provide none of these |
Allowlists and blocklists
A set of allowed or forbidden values is the cleanest way to filter data.
ALLOWED_METHODS = {"GET", "POST", "HEAD"}
requests = ["GET", "DELETE", "POST", "PATCH", "GET"]
accepted = [m for m in requests if m in ALLOWED_METHODS]
rejected = [m for m in requests if m not in ALLOWED_METHODS]
print(accepted) # ['GET', 'POST', 'GET']
print(rejected) # ['DELETE', 'PATCH']Define the set once at module level, not inside the function or loop. Rebuilding it on every call throws away the speed advantage.
Tracking what you have already seen
Algorithms that walk a graph, crawl links or process a stream need to avoid repeating work. A visited set makes each check cheap.
graph = {
"A": ["B", "C"],
"B": ["D"],
"C": ["D"],
"D": ["A"], # a cycle back to A
}
def reachable(graph, start):
visited = set()
stack = [start]
while stack:
node = stack.pop()
if node in visited:
continue
visited.add(node)
stack.extend(graph.get(node, []))
return visited
print(sorted(reachable(graph, "A"))) # ['A', 'B', 'C', 'D']Without the visited set, the cycle from D back to A would make this loop forever.
Finding the duplicates themselves
Sometimes you want to know which values repeated, not just remove them. Use two sets: one for values seen once, one for values seen again.
def find_duplicates(items):
seen = set()
dups = set()
for x in items:
if x in seen:
dups.add(x)
else:
seen.add(x)
return dups
print(sorted(find_duplicates([3, 1, 3, 2, 1, 5]))) # [1, 3]If you also need how many times each value appears, use collections.Counter instead. A set only records presence.
Comparing two collections
Set algebra turns "what changed between these two lists?" into one line per question.
db_ids = {101, 102, 103, 104}
file_ids = {103, 104, 105}
print(sorted(file_ids - db_ids)) # [105]
print(sorted(db_ids - file_ids)) # [101, 102]
print(sorted(db_ids & file_ids)) # [103, 104]
print(sorted(db_ids ^ file_ids)) # [101, 102, 105]Read these as follows: file_ids - db_ids is what is in the file but missing from the database (candidates to insert). db_ids - file_ids is what is in the database but no longer in the file (candidates to delete). The intersection is what is unchanged, and the symmetric difference is everything that differs.
The comparison methods are useful for rule checks. This example checks tags against a requirement.
required = {"python", "sql"}
blocked = {"intern"}
candidate_tags = {"python", "sql", "docker"}
has_all_required = required <= candidate_tags
has_any_blocked = not blocked.isdisjoint(candidate_tags)
print(has_all_required) # True
print(has_any_blocked) # Falserequired <= candidate_tags asks "is every required tag present?". not blocked.isdisjoint(...) asks "do the two sets share any element?".
Pitfalls and edge cases
- Iterating while modifying. Adding or removing elements during a
forloop over the same set raisesRuntimeError: Set changed size during iteration. Loop over a copy, such asfor x in list(s):, or build a new set. - Relying on order. Printing a set may look sorted for small integers, but that is an implementation detail. Never depend on it. Use
sorted()for stable output. - Rebuilding the set in a loop. Writing
if x in set(big_list):inside a loop converts the list on every iteration, which is slower than using the list directly. - Mutable elements. Storing an object whose hash changes after insertion corrupts lookups. Use immutable values, or a
frozensetor tuple. - Memory. A set of N items uses more memory than a list of the same items because of the hash table's spare capacity. For very large data, check whether memory or speed matters more.
Summary of techniques
| Goal | Technique |
|---|---|
| Unique values, order irrelevant | `set(items)` |
| Unique values, keep first-seen order | `list(dict.fromkeys(items))` |
| Unique by a derived key | Loop with a `seen` set |
| Unique unhashable items | Test on `tuple(item)` or a serialized form |
| Fast repeated membership tests | Build a set once, reuse it |
| Find added or removed items | `new - old` and `old - new` |
| Check required or forbidden values | `<=` and `isdisjoint` |
| Count occurrences | `collections.Counter` |
Exercise
You have the list names = ["Zoe", "zoe", "Adam", "ADAM", "Mia"]. Write code that returns the unique names ignoring case, keeping the first spelling of each name and the original order. What does it return?
Show answer
Use a seen set keyed on the lowercase name. seen = set() result = [] for name in names: k = name.lower() if k not in seen: seen.add(k) result.append(name) The result is ['Zoe', 'Adam', 'Mia']. A plain set(names) would keep all five names, because the strings differ in case, and it would lose the order.
Exercise
A program checks if user_id in set(blocked_ids): once for each of 50,000 incoming requests, where blocked_ids is a list of 20,000 ids. Why is this slow, and how do you fix it?
Show answer
The expression set(blockedids) rebuilds a 20,000-element set on every request, so the work is about 50,000 x 20,000 operations. Build the set once before the loop, for example blocked = set(blockedids), and then test with if user_id in blocked:. Each test is then constant time on average.
Exercise
Given old = {"a", "b", "c"} and new = {"b", "c", "d", "e"}, which expressions give the items to add, the items to remove, and the items unchanged?
Show answer
Items to add: new - old, which is {'d', 'e'}. Items to remove: old - new, which is {'a'}. Unchanged items: old & new, which is {'b', 'c'}.