Python Sets: Algebra, frozenset, and Deduplication
A set is a dictionary with the values thrown away, and that framing explains almost everything about it: membership is a hash probe rather than a scan, insertion is constant time, order is unspecified, and the contents must be hashable. Teams reach for sets too late. Code that filters one list against another with nested loops, or removes duplicates by hand with an ordered check, is doing by eye what the set operators do in C. This lesson covers the four algebraic operations and the workloads each one models, the immutability rule that makes sets usable as keys, comprehension idioms for deduplication, and the memory bill you pay for all that speed.
What You'll Learn
- 1Map union, intersection, difference, and symmetric difference onto real data tasks
- 2Decide when a set is the right container and when a list still wins
- 3Use frozenset to make sets hashable as dictionary keys and set members
- 4Estimate set memory cost and choose approximation strategies for huge inputs
Membership, hashing, and the rules of the container
Sets accept only hashable elements, the same rule that governs dictionary keys. Strings, numbers, and tuples of hashables qualify; lists and other sets do not, because their contents can change after insertion and the hash would drift. Uniqueness is enforced at insertion: adding an element that already exists is a no-op that reports success rather than an error, which makes sets ideal for streaming deduplication where you never know in advance what has arrived.
The performance consequence is the whole point. value in some_set computes one hash and probes one bucket, so lookup stays roughly constant as the set grows. value in some_list walks elements until it finds a match or reaches the end. For a membership test repeated inside a loop, converting the list to a set once before the loop is usually the single highest-leverage edit available â the conversion itself is linear, and every subsequent test is constant.
seen = set()
stream = [3, 1, 4, 1, 5, 9, 2, 6, 5]
for value in stream:
seen.add(value)
print(seen) # {1, 2, 3, 4, 5, 6, 9}
print(len(seen), len(stream)) # 7 9
print(4 in seen, 7 in seen) # True False
try:
seen.add([1, 2])
except TypeError as exc:
print("unhashable:", exc)
print(set(stream)) # dedup in one call, order not guaranteed
print(list(dict.fromkeys(stream))) # dedup that preserves first-seen order
That last line is worth memorising. Sets are unordered, so if duplicate removal must preserve the original sequence, a dictionary is the container that gives you both deduplication and order.
The four operations and the jobs they model
Union combines everything, intersection keeps what both sides share, difference removes one side's members from the other, and symmetric difference keeps only what is exclusive to each. Every one of them has a direct data-processing translation, and picking the right one often removes a nested loop entirely.
| Operation | Symbol | Method | Typical workload |
|---|---|---|---|
| Union | vertical bar | union or A | B | Merge two audiences, combine tag sets |
| Intersection | ampersand | intersection or A & B | Common customers, shared permissions, co-occurrence |
| Difference | minus | difference or A - B | Users who churned, unused features, expired IDs |
| Symmetric difference | caret | symmetric_difference or A ^ B | Changed records, XOR-style anomaly detection |
| Subset | <= | issubset or A <= B | Validate that one role is contained in another |
| Disjoint test | none | isdisjoint | Fast early exit when overlap means failure |
The isdisjoint call deserves special mention: it short-circuits on the first shared element, which makes it far cheaper than computing the full intersection just to ask whether anything overlaps. Use it in validation and filtering paths where the answer is boolean rather than structural.
active = {"alice", "bob", "carol", "dave"}
billing = {"bob", "dave", "erin", "frank"}
print(active | billing) # {'alice', 'bob', 'carol', 'dave', 'erin', 'frank'}
print(active & billing) # {'bob', 'dave'} â billed and active
print(active - billing) # {'alice', 'carol'} â active, never billed
print(active ^ billing) # {'alice', 'carol', 'erin', 'frank'} â exactly one side
print({"alice"} <= active, active <= active) # True True
print(active.isdisjoint({"zoe"})) # True
active.add("bob")
print(active) # unchanged â duplicate insertion is a no-op
Operator forms and method forms are interchangeable, with one exception: the operators require sets on both sides, while methods accept any iterable and will happily deduplicate a list or a tuple on the spot. When the right-hand operand might not be a set, the method is the safer spelling.
frozenset: making sets composable
Immutable sets exist for one reason â to be stored where mutability is forbidden. A set cannot be a dictionary key or an element of another set, because a change to its contents would invalidate its hash slot. frozenset resolves this by freezing the contents at construction: it keeps O(1) membership and set algebra, loses every mutating method, and becomes hashable so it can key a cache, sit inside a set of groups, or appear in a memo table.
The practical uses are more common than they first appear. Configuration flags can be canonicalised as a frozenset so that two flags written in different orders compare equal. Permission sets become valid dictionary keys, allowing a cache to store one result per distinct combination rather than one per user. And a graph algorithm can memoise on (frozenset(visited), node) without accidentally mutating state mid-traversal.
from collections import Counter
def normalise_flags(raw):
return frozenset(flag.strip().lower() for flag in raw)
a = normalise_flags(["Dark", "compact"])
b = normalise_flags(["compact", "dark", "extra"])
print(a == b, len(a & b)) # True 2 â set equality ignores order
PERMISSIONS = {
frozenset({"read"}): 10,
frozenset({"read", "write"}): 50,
frozenset({"read", "write", "admin"}): 100,
}
def price_for(grants):
return PERMISSIONS.get(frozenset(grants), 0)
print(price_for(["write", "read"])) # 50
print(price_for({"admin", "read"})) # 0 â exact combination not found
groups = Counter({frozenset({"a", "b"}): 3})
print(list(groups)[0]) # frozenset({'a', 'b'}) â hashable key
The exact-match lookup in price_for is deliberate: dictionary keys are compared for equality, not containment, so a user holding only two of three grants falls through to the default. When you need "any subset matches", iterate the combinations or store a lattice of supersets instead.
Comprehensions, deduplication, and derived sets
Set comprehensions mirror list comprehensions but collapse duplicates automatically, which makes them the natural tool for extracting distinct attributes from a stream of records. Chained iteration inside the comprehension handles flattening, and a trailing condition filters before insertion, so the deduplication cost is paid only on elements you actually keep.
Two discipline points separate good use from accidental over-engineering. First, a set comprehension materialises everything: for a stream that may be large, a loop with an explicit seen set lets you stop early or yield results incrementally. Second, comprehension conditions that grow beyond a simple predicate are a sign that a helper function would read better â a named function can be tested once and reused in the loop version of the same logic.
events = [
{"user": "alice", "action": "login"},
{"user": "bob", "action": "purchase"},
{"user": "alice", "action": "logout"},
{"user": "alice", "action": "purchase"},
]
users = {e["user"] for e in events}
print(users) # {'alice', 'bob'}
purchasers = {e["user"] for e in events if e["action"] == "purchase"}
print(purchasers) # {'alice', 'bob'}
by_action = {e["action"] for e in events}
print(sorted(by_action)) # ['login', 'logout', 'purchase']
tokens = {"the quick", "quick brown", "brown fox"}
words = {word for phrase in tokens for word in phrase.split()}
print(sorted(words)) # ['brown', 'fox', 'quick', 'the']
print(set("mississippi")) # {'m', 'p', 'i', 's'}
Note the difference between the derived set and the sorted output. Printing a set directly gives an arbitrary order that varies between runs and interpreters, so any assertion, log line, or user-facing list built from a set should be sorted first â a habit that prevents a whole family of flaky tests.
Choosing between list, set, and dict
The container choice should follow the access pattern, not habit. If you index by position, preserve order, or iterate in a stable sequence, you want a list. If you test membership, deduplicate, or compute overlaps, you want a set. If you look values up by key or need deterministic iteration order, you want a dict. Reaching for the wrong one is not merely slower â it often forces awkward code that exists only to compensate for the container's shape.
| Question you are answering | Best container | Why it wins |
|---|---|---|
| What is the next item? | list | Positional index and stable order |
| Have I seen this before? | set | Constant-time probe, no duplicates |
| What is the value for this key? | dict | Direct lookup with preserved order |
| Which items appear on both sides? | set | Intersection in one call |
| What order did items arrive in? | list or dict.fromkeys | Order is a property of sequence containers |
| Which combinations occurred? | set of frozenset | Hashable, unique, algebra still available |
One subtlety worth flagging: iterating a set has no guaranteed order, but that does not mean it is random per iteration either â within one process, traversal order follows the table layout and changes only when the set resizes. Code that accidentally depends on this appears to work and then breaks after unrelated data changes, so never rely on it.
Memory, sizing, and approximate membership
Sets are not free. Each entry carries hash-table overhead â an open-addressed table holds spare slots to keep probes short, so a set of ten million integers can occupy several hundred megabytes where a list of the same integers uses far less. Python's sys.getsizeof shows the table but not the elements it references, which makes naive measurements understate the cost; measure with a representative sample and multiply.
The decision rule is simple. If you will perform membership tests more than a handful of times, a set is worth its memory. If the test happens once, sorting and bisecting or building a set just for the query may be cheaper than carrying it. If the input is too large for memory altogether, you need either an external sort, a Bloom filter for approximate membership with tunable false positives, or a database index â the standard library has no probabilistic structure, but the trade-offs are worth knowing before you reach for a container that will not fit.
Common Mistakes
Iterating a set and printing or asserting on its order
Fix: Convert with sorted(...) before any output or comparison; set order is unspecified and changes on resize
Using a set where first-seen order matters
Fix: Deduplicate with dict.fromkeys, which preserves insertion order while still collapsing duplicates
Putting lists or dicts inside a set or using them as dict keys
Fix: Wrap in a tuple or frozenset, or use an unhashable-aware key such as a canonical string
Computing a full intersection just to test for overlap
Fix: Call isdisjoint, which returns as soon as one shared element is found
Converting a huge list to a set for a single membership query
Fix: Sort once and use bisect, or push the predicate into the database or source that produced the list
Best Practices
- Build membership sets before the loop that needs them, not inside it
- Sort set-derived output so tests, logs, and UI are deterministic
- Reach for frozenset when combinations of values must be dictionary keys
- Prefer set operators for clarity and methods when the other operand might not be a set
- Measure memory with representative data before caching large sets process-wide
Interview Questions
Q1: Why can a set not contain another set?
Set elements must be hashable, and a mutable set has no stable hash â adding an element would change the hash after insertion. frozenset is the immutable variant designed for exactly this case.
Q2: How do you remove duplicates from a list while keeping the original order?
Use dict.fromkeys, which relies on the guaranteed insertion order of dictionaries: list(dict.fromkeys(items)) returns first-seen order. A set comprehension would lose that order entirely.
Q3: When is set intersection the wrong tool for an overlap test?
When you only need a boolean answer or the inputs are huge. intersection builds and returns a new set; isdisjoint short-circuits on the first match and allocates nothing.
Key Takeaways
- Sets give constant-time membership by hashing, which is why they beat nested list scans
- Union, intersection, difference, and symmetric difference map directly onto four common data tasks
- Mutable sets are unhashable; frozenset exists so combinations can be keys and members
- Set order is unspecified, so sort before displaying or asserting
- Memory is the price of speed: measure before keeping a large set resident