Which customers bought from you this month and last month? Which students passed maths or science? Which IDs are in the training data but not in the test data? These are questions about groups of things: what's in both, what's in either, what's in one but not the other.
In maths, a group of things is called a set, and there's a short notation for working with them: ∈, ⊆, ∪, ∩. You'll see it in probability (events are sets), in ML papers (x ∈ ℝⁿ), and in SQL joins and pandas filters, which are set operations under the hood. Python even has sets built in.
This lesson explains sets from scratch: the symbols, the main operations with Venn diagrams, the number sets like ℝ that appear in every ML paper, set-builder notation, and how to use all of it in Python.
What you need first: maths notation and symbols and inequalities explained.
Key terms
- Set: a collection of distinct items, written in curly brackets: {2, 4, 6}.
- Element (or member): an item in a set.
- Subset: a set whose elements are all inside another set.
- Union: everything in either set.
- Intersection: only what's in both sets.
- Cardinality: the number of elements in a set.
What is a set?
A set is a collection of things, written inside curly brackets:
- A = {1, 2, 3, 4}
- Colours = {red, green, blue}
- Vowels = {a, e, i, o, u}
Two rules make sets different from lists:
- No duplicates: {1, 2, 2, 3} is the same set as {1, 2, 3}.
- No order: {1, 2, 3} is the same set as {3, 1, 2}.
Sets are usually named with capital letters, and their elements with small letters.
The basic symbols
| Symbol | Meaning | Example |
|---|---|---|
| ∈ | is an element of | 3 ∈ {1, 2, 3} |
| ∉ | is not an element of | 7 ∉ {1, 2, 3} |
| { } or ∅ | the empty set, with nothing in it | the set of months with 32 days = ∅ |
| |A| | the number of elements (cardinality) | |{a, e, i, o, u}| = 5 |
| A ⊆ B | A is a subset of B: everything in A is also in B | {1, 2} ⊆ {1, 2, 3} |
| A = B | the same elements | {1, 2} = {2, 1} |
Read x ∈ A as "x is in A" or "x belongs to A". It's Python's in: 3 in {1, 2, 3} is True.
Set operations
Take two sets of students: A took Python, B took SQL.
- A = {Asha, Ben, Chen, Divya}
- B = {Ben, Divya, Eli}
| Operation | Symbol | Meaning | Result |
|---|---|---|---|
| Union | A ∪ B | in A or B (or both) | {Asha, Ben, Chen, Divya, Eli} |
| Intersection | A ∩ B | in A and B | {Ben, Divya} |
| Difference | A − B (or A \ B) | in A but not B | {Asha, Chen} |
| Symmetric difference | A △ B | in exactly one of them | {Asha, Chen, Eli} |
| Complement | Aᶜ (or A′) | everything not in A | depends on the "universe" of everything |
Memory tricks: ∪ looks like a cup that holds everything, a U for Union. ∩ looks like an upside-down cup, and gives the overlap.
Venn diagrams
A Venn diagram draws each set as a circle; overlaps show shared elements:
import matplotlib.pyplot as plt
from matplotlib.patches import Circle
fig, ax = plt.subplots(figsize=(7, 4.5))
ax.add_patch(Circle((-0.6, 0), 1.2, alpha=0.35, color="tab:blue"))
ax.add_patch(Circle((0.6, 0), 1.2, alpha=0.35, color="tab:orange"))
ax.text(-1.2, 1.35, "A: Python", ha="center", fontsize=12)
ax.text(1.2, 1.35, "B: SQL", ha="center", fontsize=12)
ax.text(-1.1, 0, "Asha\nChen", ha="center", va="center", fontsize=11)
ax.text(0, 0, "Ben\nDivya", ha="center", va="center", fontsize=11)
ax.text(1.1, 0, "Eli", ha="center", va="center", fontsize=11)
ax.text(0, -1.55, "overlap = A ∩ B, everything shaded = A ∪ B", ha="center")
ax.set_xlim(-2.2, 2.2)
ax.set_ylim(-1.8, 1.7)
ax.set_aspect("equal")
ax.axis("off")
plt.show()
Counting with Venn diagrams
How many students took at least one course? Adding |A| + |B| = 4 + 3 = 7 counts Ben and Divya twice. Subtract the overlap:
|A ∪ B| = |A| + |B| − |A ∩ B| = 4 + 3 − 2 = 5
This is called inclusion-exclusion, and the same formula, with probabilities instead of counts, is the addition rule of probability: P(A or B) = P(A) + P(B) − P(A and B).
Sets in Python
Python has a built-in set type, with operators that match the maths:
python_users = {"Asha", "Ben", "Chen", "Divya"}
sql_users = {"Ben", "Divya", "Eli"}
print(sorted(python_users | sql_users))
print(sorted(python_users & sql_users))
print(sorted(python_users - sql_users))
print(sorted(python_users ^ sql_users))
print("Eli" in sql_users, len(python_users))
print({"Ben", "Divya"} <= sql_users)
['Asha', 'Ben', 'Chen', 'Divya', 'Eli']
['Ben', 'Divya']
['Asha', 'Chen']
['Asha', 'Chen', 'Eli']
True 4
True
| Maths | Python |
|---|---|
| A ∪ B | A | B |
| A ∩ B | A & B |
| A − B | A - B |
| A △ B | A ^ B |
| x ∈ A | x in A |
| A ⊆ B | A <= B |
| |A| | len(A) |
Sets have no order, so sorted() is used to print them in a predictable order.
A real use: checking for data leakage
If the same customer appears in both your training data and your test data, your model's test score will be too optimistic. A set intersection finds them instantly:
train_ids = {101, 102, 103, 104, 105}
test_ids = {105, 106, 107}
print(train_ids & test_ids)
{105}
Customer 105 is in both, which is a leak to fix before evaluating. Train, validation and test split explains why it matters. In pandas, the same idea is df["id"].isin(other_ids).
Measuring similarity: Jaccard
How similar are two sets? The Jaccard similarity divides the overlap by the union: |A ∩ B| / |A ∪ B|. For the students: 2/5 = 0.4. It's used to compare shopping baskets, documents (as sets of words) and recommendations.
The number sets
ML papers use special bold letters for important sets of numbers, from types of numbers:
| Symbol | Name | Contains |
|---|---|---|
| ℕ | natural numbers | 1, 2, 3, … (sometimes 0 too) |
| ℤ | integers | …, −2, −1, 0, 1, 2, … |
| ℚ | rational numbers | fractions, like ½ and −3/4 |
| ℝ | real numbers | every point on the number line |
Each sits inside the next: ℕ ⊆ ℤ ⊆ ℚ ⊆ ℝ.
ℝⁿ: the most common symbol in ML papers
ℝⁿ means "lists of n real numbers". So:
- x ∈ ℝ³ says "x is a list of 3 real numbers", like (1200, 2, 10): one house's area, bedrooms and age.
- x ∈ ℝ⁷⁸⁴ is a 28 × 28 image, flattened into 784 pixel values.
- w ∈ ℝᵈ says the model has d weights.
When a paper writes x ∈ ℝᵈ, it's simply telling you the shape of the data: d numbers per example. These lists are vectors, the topic of the Linear algebra course.
Set-builder notation
Instead of listing every element, you can describe them with a rule:
{x ∈ ℝ | x > 0}
Read it as: "the set of real numbers x such that x is greater than 0". The bar | (sometimes a colon) means "such that".
| Set-builder | In words | Interval |
|---|---|---|
| {x ∈ ℝ | x > 0} | positive real numbers | (0, ∞) |
| {x ∈ ℝ | 0 ≤ x ≤ 1} | real numbers from 0 to 1 | [0, 1] |
| {n ∈ ℤ | n is even} | even integers |
You've already met the same idea in code. A Python set comprehension is set-builder notation:
print(sorted({n for n in range(1, 21) if n % 3 == 0}))
[3, 6, 9, 12, 15, 18]
{n ∈ ℕ | n ≤ 20 and n is divisible by 3}, written in Python.
A probability, for instance, is often described as p ∈ [0, 1]: the interval notation you've already met is a compact way to write a set of numbers.
Practice
- A = {1, 3, 5, 7} and B = {3, 4, 5, 6}. Find A ∪ B, A ∩ B and A − B.
Show the answer
A ∪ B = {1, 3, 4, 5, 6, 7}. A ∩ B = {3, 5}. A − B = {1, 7}.
- True or false: (a) 4 ∈ A (b) {3, 5} ⊆ A (c) |B| = 4
Show the answer
(a) False (b) True (c) True
- In a class, 18 students like tea, 15 like coffee, and 7 like both. How many like at least one?
Show the answer
18 + 15 − 7 = 26.
- What does x ∈ ℝ⁵ tell you about x?
Show the answer
x is a list (vector) of 5 real numbers, such as one row of a table with 5 numeric columns.
- Write {x ∈ ℝ | −1 < x ≤ 4} in interval notation, and as a Python condition.
Show the answer
(−1, 4]. In Python: -1 < x <= 4.
Key takeaways
- A set is a collection of distinct items with no order, written in { }.
- x ∈ A means x is in A; A ⊆ B means every element of A is in B.
- ∪ is "or" (union), ∩ is "and" (intersection), − is "but not" (difference).
- |A ∪ B| = |A| + |B| − |A ∩ B| avoids double counting.
- ℝ is the real numbers; x ∈ ℝⁿ means x is a list of n numbers.
- Python sets use
|,&,-,inand<=; set comprehensions are set-builder notation.
Frequently asked questions
What do the symbols ∪ and ∩ mean?
∪ is union: everything that's in either set. ∩ is intersection: only what's in both sets. For {1, 2} and {2, 3}, the union is {1, 2, 3} and the intersection is {2}.
What does ∈ mean in maths?
"Is an element of" or "belongs to". 3 ∈ {1, 2, 3} means 3 is in the set. In ML, x ∈ ℝⁿ means x is a vector of n real numbers.
What is ℝ in maths?
The set of all real numbers: every number on the number line, including whole numbers, fractions and irrational numbers like π. ℝⁿ is the set of lists of n real numbers.
What to learn next
- Read the little numbers on variables in subscripts and indices explained.
- Revisit product notation (Π) explained.