Python Sets
A set is an unordered collection of unique items. Sets are perfect for removing duplicates, for fast "is this in here?" checks, and for comparing groups — which items do two groups share, which are only in one?
tags = {"python", "web", "python", "data"}
print(len(tags)) # the duplicate was dropped
print("web" in tags)
print(sorted(tags))3
True
['data', 'python', 'web']
Note: Sets have no order. Printing a set of strings may show the items in a different order each time you run the program. In this course we often print
sorted(my_set)to keep the output predictable.
Key properties
| Property | Meaning |
|---|---|
| Unordered | No indexes, no slicing |
| Unique | Duplicates are removed automatically |
| Mutable | You can add and remove items |
| Hashable items only | Items must be immutable: numbers, strings, tuples — not lists |
Creating sets
primes = {2, 3, 5, 7}
letters = set("banana") # from any iterable
empty = set() # NOT {} - that is an empty dict
print(primes)
print(sorted(letters))
print(type(empty).__name__, type({}).__name__){2, 3, 5, 7}
['a', 'b', 'n']
set dict
Removing duplicates
The fastest way to deduplicate a list is to pass it through a set. If you need to keep the original order, use dict.fromkeys() instead:
visits = ["home", "about", "home", "blog", "about", "home"]
print(len(set(visits)), "unique pages")
print(list(dict.fromkeys(visits))) # unique, original order kept3 unique pages
['home', 'about', 'blog']
Adding and removing
| Method | Effect |
|---|---|
add(x) |
Add one item |
update(iterable) |
Add many items |
remove(x) |
Remove x, KeyError if missing |
discard(x) |
Remove x if present, no error otherwise |
pop() |
Remove and return an arbitrary item |
clear() |
Remove everything |
seen = {1, 2}
seen.add(3)
seen.add(2) # already present: nothing happens
seen.update([4, 5])
seen.discard(10) # safe even though 10 is absent
seen.remove(1)
print(seen){2, 3, 4, 5}
Set operations
This is where sets shine. They support the operations you may remember from maths class, both as operators and as methods:
| Operation | Operator | Method | Result contains |
|---|---|---|---|
| Union | a | b |
a.union(b) |
items in either set |
| Intersection | a & b |
a.intersection(b) |
items in both |
| Difference | a - b |
a.difference(b) |
items in a but not b |
| Symmetric difference | a ^ b |
a.symmetric_difference(b) |
items in exactly one |
python_devs = {"An", "Binh", "Chau", "Duc"}
rust_devs = {"Chau", "Duc", "Giang"}
print(sorted(python_devs | rust_devs))
print(sorted(python_devs & rust_devs))
print(sorted(python_devs - rust_devs))
print(sorted(python_devs ^ rust_devs))['An', 'Binh', 'Chau', 'Duc', 'Giang']
['Chau', 'Duc']
['An', 'Binh']
['An', 'Binh', 'Giang']
Subsets and supersets
required = {"read", "write"}
granted = {"read", "write", "delete"}
print(required <= granted) # subset
print(granted.issuperset(required))
print(required.isdisjoint({"admin"})) # no items in commonTrue
True
True
Frozen sets
A frozenset is an immutable set. Because it can't change, it is hashable and can be used as a dictionary key or stored inside another set:
pair = frozenset({"x", "y"})
groups = {pair, frozenset({"z"})}
print(len(groups))
print(frozenset({"y", "x"}) in groups)2
True
Tip: Checking
x in some_setis very fast even for millions of items, whilex in some_listhas to scan the whole list. If you test membership in a loop, convert the list to a set first.
Test yourself
How do you create an empty set?
- {}
- set()
- []
- empty_set()
What is {1, 2, 3} & {2, 3, 4}?
- {1, 2, 3, 4}
- {2, 3}
- {1, 4}
- {1}
Which method removes an item without raising an error if it's missing?
- remove()
- pop()
- discard()
- delete()