Sets
A set is a collection of distinct objects, where order does not matter and nothing appears twice. Sets are the language in which the rest of mathematics is written: domains of functions, solution sets of equations and intervals on the number line are all sets. Python has sets built in, so we will use them as a running model throughout.
Notation
A set is written with braces: . The objects in it are its elements.
| Notation | Meaning | Python |
|---|---|---|
| is an element of | x in A |
|
| is not an element of | x not in A |
|
| or | the empty set | set() (not {}, which is a dict) |
| the number of elements (cardinality) | len(A) |
|
| is a subset of : every element of is in | A <= B |
|
| proper subset: and | A < B |
|
| same elements | A == B |
Two sets are equal when they have the same elements, regardless of order or repetition: .
Sets can be described by listing (roster notation) or by a rule (set-builder notation):
Python's set comprehension is set-builder notation almost word for word:
E = {x for x in range(0, 11) if x % 2 == 0}
print("E =", sorted(E), " |E| =", len(E))
print("{1, 2, 2, 3} == {3, 1, 2}:", {1, 2, 2, 3} == {3, 1, 2})
print("4 in E:", 4 in E, " 5 in E:", 5 in E)
print("{2, 4} ⊆ E:", {2, 4} <= E, " E ⊆ E:", E <= E, " E ⊂ E:", E < E)
print("type of {}:", type({}).__name__, " type of set():", type(set()).__name__)E = [0, 2, 4, 6, 8, 10] |E| = 6
{1, 2, 2, 3} == {3, 1, 2}: True
4 in E: True 5 in E: False
{2, 4} ⊆ E: True E ⊆ E: True E ⊂ E: False
type of {}: dict type of set(): set
Tip: Python sets have no guaranteed order. Print
sorted(s)when you want stable output; for sets of strings the order can even change between program runs.
Operations
| Operation | Definition | Python |
|---|---|---|
| Union | in or in (or both) | A | B |
| Intersection | in both and | A & B |
| Difference (or ) | in but not in | A - B |
| Symmetric difference | in exactly one of them | A ^ B |
| Complement | everything in the universe not in | U - A |
Sets with no common elements () are disjoint. A Venn diagram draws each set as a circle inside a rectangle for , so the overlap is the intersection.
U = set(range(1, 13))
A = {x for x in U if x % 2 == 0} # even
B = {x for x in U if x % 3 == 0} # multiples of 3
for name, s in [("A ∪ B", A | B), ("A ∩ B", A & B), ("A \\ B", A - B),
("A △ B", A ^ B), ("Aᶜ", U - A)]:
print(f"{name:6} = {sorted(s)}")
# De Morgan's laws
print("(A ∪ B)ᶜ == Aᶜ ∩ Bᶜ:", U - (A | B) == (U - A) & (U - B))
print("(A ∩ B)ᶜ == Aᶜ ∪ Bᶜ:", U - (A & B) == (U - A) | (U - B))A ∪ B = [2, 3, 4, 6, 8, 9, 10, 12]
A ∩ B = [6, 12]
A \ B = [2, 4, 8, 10]
A △ B = [2, 3, 4, 8, 9, 10]
Aᶜ = [1, 3, 5, 7, 9, 11]
(A ∪ B)ᶜ == Aᶜ ∩ Bᶜ: True
(A ∩ B)ᶜ == Aᶜ ∪ Bᶜ: True
De Morgan's laws say the complement of a union is the intersection of the complements, and vice versa. They are the same laws as not (p or q) == (not p) and (not q) in Boolean logic.
Counting: inclusion-exclusion
Adding and counts the overlap twice, so
In the example above: , matching the eight elements of .
Products and power sets
The Cartesian product is the set of all ordered pairs with and , and . The coordinate plane is . The power set is the set of all subsets of ; a set with elements has subsets, because each element is either in or out.
from itertools import product, combinations
A = {"x", "y", "z"}
pairs = sorted(product(["H", "T"], [1, 2, 3]))
print("|{H,T} × {1,2,3}| =", len(pairs), pairs[:3], "...")
subsets = [set(c) for r in range(len(A) + 1) for c in combinations(sorted(A), r)]
print("power set size:", len(subsets), "= 2^3")
print([sorted(s) for s in subsets])|{H,T} × {1,2,3}| = 6 [('H', 1), ('H', 2), ('H', 3)] ...
power set size: 8 = 2^3
[[], ['x'], ['y'], ['z'], ['x', 'y'], ['x', 'z'], ['y', 'z'], ['x', 'y', 'z']]
Number sets and intervals
The standard number sets are nested: (natural numbers, integers, rationals, reals, complex numbers). Subsets of that are unbroken stretches are written as intervals:
| Interval | Set-builder | Brackets |
|---|---|---|
| closed: endpoints included | ||
| open: endpoints excluded | ||
| half-open | ||
| always gets a round bracket |
Intervals are infinite sets, so Python's set cannot hold them, but SymPy can: Interval(0, 2) ∪ Interval(1, 5) is [0, 5]. You will use intervals for the domains and ranges of functions.
In software
- Deduplication.
len(set(emails))counts distinct values;set(a) & set(b)finds common items in average time instead of nested loops, because sets are hash tables (hash tables in DSA). - Permissions. A user's permissions are the union of their roles' permission sets; an action is allowed if the required set is a subset of what the user has. Deny lists are a set difference.
- SQL has
UNION,INTERSECTandEXCEPT, which are , and on rows. - Feature flags, tags and graph algorithms (the
visitedset in a breadth-first search) are all sets.
ROLES = {
"viewer": {"read"},
"editor": {"read", "write", "comment"},
"admin": {"read", "write", "comment", "delete", "invite"},
}
def permissions(roles, denied=frozenset()):
perms = set().union(*(ROLES[r] for r in roles))
return perms - denied
alice = permissions(["viewer", "editor"])
bob = permissions(["admin"], denied={"delete"})
print("alice:", sorted(alice))
print("bob :", sorted(bob))
print("can alice {write, comment}?", {"write", "comment"} <= alice)
print("can bob delete?", "delete" in bob)
visits = ["ana", "ben", "ana", "cy", "ben", "ana"]
print("distinct visitors:", len(set(visits)))alice: ['comment', 'read', 'write']
bob : ['comment', 'invite', 'read', 'write']
can alice {write, comment}? True
can bob delete? False
distinct visitors: 3
Exercises
Exercise 1: Operations by hand
Let , and . Find , , and .
Answer
, , , .
Solution
U, A, B = set(range(1, 11)), {1, 2, 3, 4, 5}, {4, 5, 6, 7}
print(sorted(A | B), sorted(A & B), sorted(B - A), sorted(U - (A | B)))[1, 2, 3, 4, 5, 6, 7] [4, 5] [6, 7] [8, 9, 10]
Exercise 2: Set-builder
Write in set-builder notation, and write as an interval.
Answer
; .
Solution
The elements are the squares of 1 to 5. In the second set, −2 is excluded (round bracket) and 7 is included (square bracket).
Exercise 3: Inclusion-exclusion
In a class of 40 students, 22 code in Python, 15 in JavaScript and 7 in both. How many code in neither?
Answer
Solution
Exercise 4: Count subsets
How many subsets does have? How many of them contain ?
Answer
32 subsets; 16 contain .
Solution
. A subset containing is a choice of any subset of the other four elements, plus : .
from itertools import combinations
S = "abcde"
subs = [set(c) for r in range(6) for c in combinations(S, r)]
print(len(subs), sum("a" in s for s in subs))32 16
Exercise 5: Changed files
Two deployments contain these files. Use set operations to print the files that were added, removed, and kept.
old = {"app.py", "util.py", "config.yaml", "README.md"}
new = {"app.py", "util.py", "settings.toml", "README.md", "cli.py"}Answer
added: cli.py, settings.toml; removed: config.yaml; kept: README.md, app.py, util.py.
Solution
old = {"app.py", "util.py", "config.yaml", "README.md"}
new = {"app.py", "util.py", "settings.toml", "README.md", "cli.py"}
print("added :", sorted(new - old))
print("removed:", sorted(old - new))
print("kept :", sorted(old & new))added : ['cli.py', 'settings.toml']
removed: ['config.yaml']
kept : ['README.md', 'app.py', 'util.py']
Test yourself
What is ?
How many elements does the power set of a 4-element set have?
- 4
- 8
- 16
- 24
In Python, what does x = {} create?
- An empty set
- An empty dict
- An empty list
- A syntax error