TExcelTAD

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: A={2,3,5,7}A = \{2, 3, 5, 7\}. The objects in it are its elements.

Notation Meaning Python
x∈Ax \in A xx is an element of AA x in A
x∉Ax \notin A xx is not an element of AA x not in A
∅\emptyset or {}\{\} the empty set set() (not {}, which is a dict)
∣A∣\lvert A \rvert the number of elements (cardinality) len(A)
A⊆BA \subseteq B AA is a subset of BB: every element of AA is in BB A <= B
A⊂BA \subset B proper subset: A⊆BA \subseteq B and A≠BA \ne B A < B
A=BA = B same elements A == B

Two sets are equal when they have the same elements, regardless of order or repetition: {1,2,2,3}={3,1,2}\{1, 2, 2, 3\} = \{3, 1, 2\}.

Sets can be described by listing (roster notation) or by a rule (set-builder notation):

E={x∈Z∣0≤x≤10 and x is even}={0,2,4,6,8,10}read: "the set of integers x such that 0≤x≤10 and x is even"\begin{aligned} &E = \{ x \in \mathbb{Z} \mid 0 \le x \le 10 \text{ and } x \text{ is even} \} = \{0, 2, 4, 6, 8, 10\} \\ &\text{read: "the set of integers } x \text{ such that } 0 \le x \le 10 \text{ and } x \text{ is even"} \end{aligned}

Python's set comprehension is set-builder notation almost word for word:

python · try it yourself
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 A∪BA \cup B in AA or in BB (or both) A | B
Intersection A∩BA \cap B in both AA and BB A & B
Difference A∖BA \setminus B (or A−BA - B) in AA but not in BB A - B
Symmetric difference A△BA \mathbin{\triangle} B in exactly one of them A ^ B
Complement AcA^c everything in the universe UU not in AA U - A

Sets with no common elements (A∩B=∅A \cap B = \emptyset) are disjoint. A Venn diagram draws each set as a circle inside a rectangle for UU, so the overlap is the intersection.

python · try it yourself
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 ∣A∣\lvert A \rvert and ∣B∣\lvert B \rvert counts the overlap twice, so

∣A∪B∣=∣A∣+∣B∣−∣A∩B∣∣A∪B∪C∣=∣A∣+∣B∣+∣C∣−∣A∩B∣−∣A∩C∣−∣B∩C∣+∣A∩B∩C∣\begin{aligned} \lvert A \cup B \rvert &= \lvert A \rvert + \lvert B \rvert - \lvert A \cap B \rvert \\ \lvert A \cup B \cup C \rvert &= \lvert A \rvert + \lvert B \rvert + \lvert C \rvert - \lvert A \cap B \rvert - \lvert A \cap C \rvert - \lvert B \cap C \rvert + \lvert A \cap B \cap C \rvert \end{aligned}

In the example above: 6+4−2=86 + 4 - 2 = 8, matching the eight elements of A∪BA \cup B.

Products and power sets

The Cartesian product A×BA \times B is the set of all ordered pairs (a,b)(a, b) with a∈Aa \in A and b∈Bb \in B, and ∣A×B∣=∣A∣⋅∣B∣\lvert A \times B \rvert = \lvert A \rvert \cdot \lvert B \rvert. The coordinate plane is R×R\mathbb{R} \times \mathbb{R}. The power set P(A)P(A) is the set of all subsets of AA; a set with nn elements has 2n2^n subsets, because each element is either in or out.

python · try it yourself
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: N⊂Z⊂Q⊂R⊂C\mathbb{N} \subset \mathbb{Z} \subset \mathbb{Q} \subset \mathbb{R} \subset \mathbb{C} (natural numbers, integers, rationals, reals, complex numbers). Subsets of R\mathbb{R} that are unbroken stretches are written as intervals:

Interval Set-builder Brackets
[a,b][a, b] {x∣a≤x≤b}\{x \mid a \le x \le b\} closed: endpoints included
(a,b)(a, b) {x∣a<x<b}\{x \mid a < x < b\} open: endpoints excluded
[a,b)[a, b) {x∣a≤x<b}\{x \mid a \le x < b\} half-open
(a,∞)(a, \infty) {x∣x>a}\{x \mid x > a\} ∞\infty 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 O(n)O(n) average time instead of O(n2)O(n^2) 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, INTERSECT and EXCEPT, which are ∪\cup, ∩\cap and ∖\setminus on rows.
  • Feature flags, tags and graph algorithms (the visited set in a breadth-first search) are all sets.
python · try it yourself
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 U={1,…,10}U = \{1, \ldots, 10\}, A={1,2,3,4,5}A = \{1, 2, 3, 4, 5\} and B={4,5,6,7}B = \{4, 5, 6, 7\}. Find A∪BA \cup B, A∩BA \cap B, B∖AB \setminus A and (A∪B)c(A \cup B)^c.

Answer

A∪B={1,…,7}A \cup B = \{1, \ldots, 7\}, A∩B={4,5}A \cap B = \{4, 5\}, B∖A={6,7}B \setminus A = \{6, 7\}, (A∪B)c={8,9,10}(A \cup B)^c = \{8, 9, 10\}.

Solution
python · try it yourself
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 {1,4,9,16,25}\{1, 4, 9, 16, 25\} in set-builder notation, and write {x∈R∣−2<x≤7}\{x \in \mathbb{R} \mid -2 < x \le 7\} as an interval.

Answer

{n2∣n∈N,1≤n≤5}\{n^2 \mid n \in \mathbb{N}, 1 \le n \le 5\}; (−2,7](-2, 7].

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
∣P∪J∣=22+15−7=30neither=40−30=10\begin{aligned} \lvert P \cup J \rvert &= 22 + 15 - 7 = 30 \\ \text{neither} &= 40 - 30 = 10 \end{aligned}

Exercise 4: Count subsets

How many subsets does {a,b,c,d,e}\{a, b, c, d, e\} have? How many of them contain aa?

Answer

32 subsets; 16 contain aa.

Solution

25=322^5 = 32. A subset containing aa is a choice of any subset of the other four elements, plus aa: 24=162^4 = 16.

python · try it yourself
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.

text
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
python · try it yourself
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 {1,2,3}∩{2,3,4}\{1, 2, 3\} \cap \{2, 3, 4\}?

  1. {1,2,3,4}\{1, 2, 3, 4\}
  2. {2,3}\{2, 3\}
  3. {1,4}\{1, 4\}
  4. ∅\emptyset

How many elements does the power set of a 4-element set have?

  1. 4
  2. 8
  3. 16
  4. 24

In Python, what does x = {} create?

  1. An empty set
  2. An empty dict
  3. An empty list
  4. A syntax error