Sub topic 6
Sets: uniqueness and set operations
This chapter assumes you can write Python loops and functions, know the built-in types int, str, and bool, and have read the earlier chapters on mutability, lists, tuples, hashability, and dictionaries. In particular, you should recall that a hashable object has a hash value that never changes during its lifetime and that compares equal to other objects with the same hash.
What a set is
A set is an unordered, mutable collection of unique, hashable elements. Three properties follow from that definition:
- Unique. Adding a value that is already present changes nothing.
- Unordered. A set has no positions, so there is no indexing and no slicing.
- Hashable elements. Every element must be hashable, for the same reason dict keys must be.
Internally, a set is built on a hash table, like a dict, but it stores only keys and no values. That design is why membership tests are fast, and it is also why the elements must be hashable.
colors = {"red", "green", "blue", "red"}
print(len(colors)) # 3, the duplicate "red" is dropped
print("green" in colors) # True
colors.add("yellow")
colors.add("red") # no effect, "red" is already present
print(len(colors)) # 4
try:
print(colors[0])
except TypeError as e:
print(e) # 'set' object is not subscriptableCreating sets
Curly braces with at least one element create a set. Empty curly braces create a dict, so an empty set needs the set() constructor.
empty_dict = {}
empty_set = set()
print(type(empty_dict).__name__) # dict
print(type(empty_set).__name__) # set
letters = set("hello") # any iterable works
print(sorted(letters)) # ['e', 'h', 'l', 'o']
squares = {n * n for n in range(5)} # set comprehension
print(sorted(squares)) # [0, 1, 4, 9, 16]Note that set("hello") iterates over the string, so the set contains characters, not the whole word. To make a set holding one string, write {"hello"}.
Equality decides uniqueness
A set decides whether two elements are "the same" using hash and equality, not identity. Two objects count as duplicates when they have the same hash and compare equal. This leads to a few results that surprise people:
mixed = {1, 1.0, True}
print(mixed) # {1}
print(len(mixed)) # 1
print(hash(1) == hash(1.0) == hash(True)) # True
print(1 == 1.0 == True) # TrueBecause 1, 1.0, and True are equal and hash alike, the set keeps only the first one it sees. The same rule applies to dict keys. If your data mixes numbers and booleans, convert them to a single type before putting them in a set.
Changing a set
Sets provide several methods for adding and removing elements. The difference between remove, discard, and pop matters for error handling.
| Method | Effect | If the element is missing |
|---|---|---|
| `s.add(x)` | Adds `x` | Not applicable |
| `s.update(iterable)` | Adds every item of the iterable | Not applicable |
| `s.remove(x)` | Removes `x` | Raises `KeyError` |
| `s.discard(x)` | Removes `x` | Does nothing |
| `s.pop()` | Removes and returns an arbitrary element | Raises `KeyError` if the set is empty |
| `s.clear()` | Removes everything | Not applicable |
tags = {"python", "sets"}
tags.update(["hash", "tables"])
tags.discard("missing") # silent
try:
tags.remove("missing")
except KeyError as e:
print("KeyError:", e) # KeyError: 'missing'
removed = tags.pop() # which element you get is not defined
print(removed in tags) # FalseUse discard when absence is acceptable and remove when absence signals a bug you want to see.
Set algebra
Sets support the operations you know from mathematics. Each operation has an operator form 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 set |
a = {1, 2, 3, 4}
b = {3, 4, 5}
print(sorted(a | b)) # [1, 2, 3, 4, 5]
print(sorted(a & b)) # [3, 4]
print(sorted(a - b)) # [1, 2]
print(sorted(b - a)) # [5]
print(sorted(a ^ b)) # [1, 2, 5]The diagram below shows how a worked example splits into regions. Each region is the result of one operation.
Operators versus methods
The operator forms require both operands to be sets. The method forms accept any iterable, so they are convenient when the other side is a list or a generator.
a = {1, 2, 3}
print(sorted(a.union([3, 4, 5]))) # [1, 2, 3, 4, 5]
try:
a | [3, 4, 5]
except TypeError as e:
print(e) # unsupported operand type(s) for |: 'set' and 'list'In-place versions
Each operation also has an in-place form that modifies the left-hand set instead of building a new one: |=, &=, -=, ^=, and the methods update, intersection_update, difference_update, and symmetric_difference_update.
allowed = {"read", "write", "admin"}
allowed -= {"admin"}
print(sorted(allowed)) # ['read', 'write']Remember that in-place operations affect every name that refers to the same set object, which matters when a set is shared between functions.
Comparing sets
Sets can be compared for subset and superset relationships. These tests are useful for validating input.
required = {"name", "email"}
provided = {"name", "email", "phone"}
print(required <= provided) # True, subset
print(required < provided) # True, proper subset
print(provided >= required) # True, superset
print(required.isdisjoint({"fax"})) # True, nothing in common
print({1, 2} == {2, 1}) # True, order is irrelevantA common idiom is to report what is missing:
def missing_fields(record, required):
return required - record.keys()
print(sorted(missing_fields({"name": "Ana"}, {"name", "email"}))) # ['email']This works because dict.keys() returns a view that supports set operations. Here required is a set, and required - record.keys() returns a new set.
Practical uses
Deduplication
Passing an iterable to set() removes duplicates, but the result has no defined order. When you need to keep the first-seen order, use dict.fromkeys, which relies on dicts preserving 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]Both approaches require the items to be hashable. A list of lists cannot be deduplicated this way. Convert each inner list to a tuple first.
rows = [[1, 2], [3, 4], [1, 2]]
unique_rows = {tuple(r) for r in rows}
print(sorted(unique_rows)) # [(1, 2), (3, 4)]Fast membership tests
Testing x in some_list scans the list from the start and takes time proportional to its length. Testing x in some_set computes a hash and jumps to the right slot, which takes roughly constant time on average. If you test membership many times against the same collection, build a set once.
banned_list = ["spam", "scam", "phish"]
banned = set(banned_list)
messages = ["hello", "spam", "lunch?"]
clean = [m for m in messages if m not in banned]
print(clean) # ['hello', 'lunch?']Building the set costs time proportional to its size, so for a single lookup in a small list, converting is not worth it. The gain appears when you do many lookups.
Finding overlap
Set algebra replaces nested loops when you compare two collections.
yesterday = {"ana", "ben", "cy"}
today = {"ben", "cy", "dee"}
print(sorted(today - yesterday)) # ['dee'], new visitors
print(sorted(yesterday - today)) # ['ana'], visitors who did not return
print(sorted(yesterday & today)) # ['ben', 'cy'], returning visitorsSets of sets
An element of a set must be hashable, and a set is mutable, so a set cannot contain another set. The immutable frozenset solves this and is covered in a later chapter.
try:
nested = {{1, 2}, {3}}
except TypeError as e:
print(e) # unhashable type: 'set'
nested = {frozenset({1, 2}), frozenset({3})}
print(len(nested)) # 2Common errors
- Expecting a stable order. Printing a set can show elements in a different order from the one you used to build it, and string hashing is randomized between interpreter runs. Use
sorted(s)whenever the order matters, such as in output, tests, and documentation. - Using
{}for an empty set. This creates a dict. Useset(). - Putting a list or dict in a set. This raises
TypeError: unhashable type. Convert lists to tuples first. - Modifying a set while iterating over it. Python raises
RuntimeError: Set changed size during iteration. Iterate over a copy, such asfor x in list(s), or build a new set. - Relying on
pop()to return a particular element. It removes an arbitrary element. If you need the smallest or the first inserted, a set is the wrong tool. - Assuming that equal numbers are distinct.
1,1.0, andTruecollapse into one element.
s = {1, 2, 3, 4}
for x in list(s):
if x % 2 == 0:
s.remove(x)
print(sorted(s)) # [1, 3]Deciding whether a set fits
Reach for a set when the question you ask most often is "is this value present?", "what do these two collections share?", or "which values are unique?" Avoid it when you need order, duplicates with counts, or access by position. For counts, a dict or collections.Counter fits better. For order with uniqueness, use dict.fromkeys or a list guarded by a set of values already seen.
exercise
Q: You have `emails = ["[email protected]", "[email protected]", "[email protected]", "[email protected]"]` and `unsubscribed = {"[email protected]"}`. Write one expression that gives the sorted list of unique addresses that are still subscribed.
A: `sorted(set(emails) - unsubscribed)` returns `['[email protected]', '[email protected]']`. The `set(emails)` call removes the duplicate, the `-` operator removes unsubscribed addresses, and `sorted` produces a predictable list.Exercise
Why does {1, 2} | [3] raise a TypeError while {1, 2}.union([3]) returns {1, 2, 3}?
Show answer
The | operator requires both operands to be sets (or frozensets), so a list on the right is rejected. The union method accepts any iterable and builds the result from its items.
Exercise
What does len({1, 1.0, True, "1"}) return, and why?
Show answer
It returns 2. The values 1, 1.0, and True are equal and share a hash, so they collapse into a single element. The string "1" is not equal to the number 1, so it stays as a second element.