Sub topic 6
Sets: uniqueness and set operations
This chapter assumes you know Python lists, tuples, and dictionaries at a basic level. You should also know what hashable means: an object whose hash value never changes and that can be compared for equality. The previous chapter covered why dict keys must be hashable. Set elements follow the same rule.
The working model
A set is an unordered collection of unique, hashable elements. It stores only values, with no keys and no positions. Python uses a hash table internally, so it can check whether a value is present without scanning every element.
Three properties follow from that design:
- Each element appears at most once. Adding a duplicate does nothing.
- There is no index.
s[0]raises aTypeError. - Elements must be hashable, so you can store numbers, strings, and tuples of those. You cannot store lists, dicts, or other sets.
Create a set with braces or with set(). Empty braces {} create an empty dict, so use set() for an empty set.
primes = {2, 3, 5, 7}
letters = set("hello")
empty = set()
print(sorted(letters)) # ['e', 'h', 'l', 'o']
print(type({})) # <class 'dict'>
print(type(empty)) # <class 'set'>
primes.add(11)
primes.add(11) # no effect, 11 is already present
primes.discard(4) # no error, even though 4 is missing
print(len(primes)) # 5remove(x) raises KeyError if x is missing. discard(x) does not. Use discard when absence is acceptable.
Set operations
Sets support the operations from school mathematics. Each has an operator and a method form.
| Operation | Operator | Method | Result | Column |
|---|---|---|---|---|
| Union | `a \ | b` | `a.union(b)` | Elements in either set |
| Intersection | `a & b` | `a.intersection(b)` | Elements in both | |
| Difference | `a - b` | `a.difference(b)` | Elements in `a` but not `b` | |
| Symmetric difference | `a ^ b` | `a.symmetric_difference(b)` | Elements in exactly one |
The operators require both sides to be sets. The methods accept any iterable, so a.union([5, 6]) works while a | [5, 6] raises a TypeError.
a = {1, 2, 3}
b = {2, 3, 4}
print(sorted(a & b)) # [2, 3]
print(sorted(a | b)) # [1, 2, 3, 4]
print(sorted(a - b)) # [1]
print(sorted(a ^ b)) # [1, 4]
print(2 in a) # True
print({1, 2} <= a) # True, subset test
print(a.isdisjoint({9})) # True, no shared elementsSets have no defined order for printing, so these examples use sorted to show predictable output.
Deduplication
The most common use of a set is removing duplicates. Converting a list to a set discards repeats, but the order is not preserved. If you need first-seen order, use dict.fromkeys, because dicts keep insertion order.
items = [3, 1, 3, 2, 1]
unique_any_order = set(items)
unique_in_order = list(dict.fromkeys(items))
print(len(unique_any_order)) # 3
print(unique_in_order) # [3, 1, 2]Membership tests
Checking x in my_set takes constant time on average. Checking x in my_list scans the list, which takes time proportional to its length. When you test membership many times against the same collection, build a set once.
allowed = {"read", "write", "admin"}
requests = ["read", "delete", "write", "ban"]
denied = [r for r in requests if r not in allowed]
print(denied) # ['delete', 'ban']Common errors
- Using
{}for an empty set. It creates a dict. Useset(). - Putting a list in a set.
{[1, 2]}raisesTypeError: unhashable type: 'list'. Convert the inner list to a tuple first. - Relying on order. The iteration order of a set is not something to depend on. Sort when you need stable output.
- Mutating while iterating. Adding or removing elements during a loop over the same set raises
RuntimeError. Loop over a copy withset(s)instead. - Expecting
1andTrueto differ. They are equal and have the same hash, so a set treats them as one element.
Exercise
Given a = [1, 2, 2, 3] and b = [3, 4, 4, 5], write one expression that gives the sorted list of values that appear in both lists, and explain why you used sets.
Show answer
sorted(set(a) & set(b)) returns [3]. Converting to sets removes duplicates and makes the intersection operator available. Each membership check inside the intersection is a constant-time hash lookup on average, so it avoids nested scans of both lists. sorted is needed because sets have no defined order.
Exercise
Why does {[1, 2], [3, 4]} fail, and how would you store the same data in a set?
Show answer
Lists are mutable and therefore unhashable, so a set cannot place them in its hash table. It raises TypeError: unhashable type: 'list'. Convert each list to a tuple: {(1, 2), (3, 4)}.