Lesson · Core Collections
Sets & Frozensets
57 min readSets & Frozensets
Sets model unique hashable values and make membership and set algebra efficient. `frozenset` provides an immutable, hashable version when a set itself must be used as a key or member.
Learning goals
- Predict the four set algebra results in the worked example (
|,&,-,^) before running any of them. - Explain why membership tests in a set are much faster than the same test in a list.
- Deduplicate a sequence with
set(...), state what that costs (order and type), and keep first-seen order withdict.fromkeys(...)when needed. - Use a
frozensetas a dict key and say why its plainsetcounterpart cannot take that role. - Match each operation to its method and operator forms, including which forms accept any iterable.
Mental model
Every operation here is the same underlying table seen from a different side: uniqueness is what deduplication exposes, membership is a single probe, and the algebra builds a new table from two. The frozenset exists for the moment a set has to sit somewhere that demands a stable hash, such as a dictionary key or a member of another set.
One table, four questions asked of it
a = {1, 2, 3} b = {3, 4, 5}
Mental model
the same mechanism as a compact list
set → a hash table of unique values ↓ ask "is it in there?" → one hash probe (fast) against a full scan (slow) ↓ combine two sets → | union, & intersection, - difference, ^ symmetric difference ↓ need order or duplicates? a set is the wrong tool; use dict.fromkeys for first-seen order ↓ need the set itself as a key? frozenset, immutable and hashable
Core idea
A set is a dictionary that stores only keys: uniqueness, fast membership, and the algebra of |, &, -, and ^ all come from that one design. The operations return new sets and leave the originals untouched, while the method forms accept any iterable (a.union([9])), which the operator forms do not. frozenset is the same table with immutability added, and that is exactly what makes it usable as a dict key or a member of another set.
Creation
Creation in Sets & Frozensets means constructing a new object with valid initial state. Compare literal syntax, constructors, and factory-style APIs where they exist, and note whether construction copies or reuses existing objects.
Membership
Membership uses in and not in to ask whether a value is present. The underlying cost depends on the container protocol and data structure, so list membership and set membership have very different performance profiles.
Deduplication
A set can remove duplicate hashable values, but converting to a set changes the collection type and does not serve every ordering requirement. A dictionary-based pattern can preserve first-seen order.
Union
Union is a set operation that produces all elements from either set. Python supports method forms and operator forms for these operations.
Intersection
Intersection is a set operation that produces elements present in both sets. Python supports method forms and operator forms for these operations.
Difference
Difference is a set operation that produces elements in the left set but not the right. Python supports method forms and operator forms for these operations.
Symmetric difference
Symmetric difference is a set operation that produces elements present in exactly one of the sets. Python supports method forms and operator forms for these operations.
Subset / superset
Subset and superset relations compare set inclusion rather than element counts alone. The strict forms exclude equality.
Set comprehensions
A set comprehension evaluates an expression for selected input items and keeps only unique hashable results.
frozenset
frozenset is an immutable set type. Because it cannot change after construction, it can be hashable when all its elements are hashable.
Hashability
Hashability means an object can be stored in a hash table: it has a hash value that stays constant during its lifetime and supports equality comparison. Built-in immutable types such as int, str, and frozenset are hashable, so they can be set members or dict keys, while list, dict, and set are not and raise TypeError: unhashable type when used in those positions. A frozenset is hashable only if every element inside it is hashable.
Walkthrough
a | breturns a new set holding every value from both sides, whilea & bkeeps only the shared3; none of the operators mutateaorb, so the originals still hold their values afterwards.a - bremoves every value ofbfroma, leaving{1, 2}, anda ^ bkeeps values that appear in exactly one set, so the shared3drops out of both.frozenset({"read", "write"})is hashable, which is what lets it serve as the key inpermissions; a plainsetin that position raisesTypeError: unhashable type.- Predict before running: the four printed sets and whether
permissions[frozen]succeeds for afrozensetwhere asetkey would fail.
Experiments to try
- Build
aandbfromrangeinstead of literals and confirm the four operators print the same shapes; then checka <= {1, 2, 3}anda < {1, 2, 3}to see the strict form reject the equal set. - Run
a.union([9])and thena | [9]; the method accepts any iterable while the operator requires a set on both sides. - Build
{[1, 2], [3]}and read theTypeError: unhashable type: 'list'; build{(1, 2), (3,)}instead and explain why tuples pass the same check. - Deduplicate
[3, 1, 3, 2, 1]withset(...)and withlist(dict.fromkeys(...)), compare the orders, then time a membership test on a list against the same test on a set of the same values.
Common mistakes
- Expecting the operator forms to accept lists:
a | [9]raisesTypeErrorbecause|needs a set on both sides, whilea.union([9])takes any iterable. - Assuming iteration order is stable after deduplication: a
setorder follows hash table internals, so usedict.fromkeys(...)when first-seen order matters. - Forgetting that sets cannot be keys:
{ {1, 2}: "x" }raisesTypeError: unhashable type: 'set'because a mutable key could change its hash, andfrozensetis the fixed-value substitute. - Treating
a - bas symmetric like&and^: difference keeps values in the left set that are not in the right, so swapping the operands changes the result.
Practice: Easy
- Build
a = {1, 2, 3}andb = {3, 4, 5}, printa | b,a & b,a - b, anda ^ b, and label each output with the operator that produced it. - Run
len({1, 1, 2, 3, 3})and{1, 1, 2, 3, 3} == {1, 2, 3}, then explain in one sentence why the duplicates are gone before any operation runs. - Call
a.add(9), then runa | [9]anda.union([9]); record which line raises and which returns a new set, and why the two forms differ.
Practice: Medium
- Deduplicate
["b", "a", "b", "c", "a"]once withset(...)and once withlist(dict.fromkeys(...)); compare the resulting orders and state when first-seen order matters. - Use
frozenset({"read", "write"})as a dict key in a permissions lookup, then swap in the plainsetand read theTypeError: unhashable type: 'set'; explain which property of the key the dict requires. - Apply
union,intersection,difference, andsymmetric_differenceto the worked example's sets with a list argument, and confirm each method accepts the iterable where the operator forms do not.
Practice: Hard
- Design a tag filter over a list of
frozensettag sets: return the entries matching any query tag with&and all query tags with<=. Define inputs, expected outputs, and one test before implementing, using only operations from this lesson. - Build a failure lab with three cases: an unhashable element inside a set literal, a plain
setused as a dict key, and a deduplication that loses insertion order. Explain the hash table mechanism behind each result. - Connect this lesson to the complexity lesson: state the average cost of membership in a set versus a list, and describe one realistic input size where replacing a list membership scan with a set changes a script from unusable to instant.
Lesson checklist
- I can draw the four algebra results for two overlapping sets without running the code.
- I can explain why set membership beats a list scan and why
frozensetis needed once a set itself must be a key. - I can deduplicate a sequence and choose between
set(...)anddict.fromkeys(...)for ordering. - I can name the method and operator forms of each set operation and say which one accepts a list.
Remember
Sets are hash tables that store unique hashable values, which buys fast membership and the algebra of `|`, `&`, `-`, and `^`; the operators build new sets and never mutate their operands. The method forms accept any iterable, deduplication trades order for uniqueness unless `dict.fromkeys(...)` preserves first-seen order, and a `frozenset` is what you reach for when the set itself must be a key or a member of another set.
Interview angles
What is the main purpose of **Creation**?+
Creation in Sets & Frozensets means constructing a new object with valid initial state. Compare literal syntax, constructors, and factory-style APIs where they exist, and note whether construction copies or reuses existing objects.
What should you pay attention to when using **Membership**?+
Membership uses in and not in to ask whether a value is present. The underlying cost depends on the container protocol and data structure, so list membership and set membership have very different performance profiles.
How does **Deduplication** fit into this lesson?+
A set can remove duplicate hashable values, but converting to a set changes the collection type and does not serve every ordering requirement. A dictionary-based pattern can preserve first-seen order.
Why does `a | [9]` raise while `a.union([9])` works?+
The operator forms require a set on both sides, so a list operand raises TypeError; the method forms accept any iterable and convert it internally, which is why a.union([9]) returns a new set.