Module contents
Lesson 3 of 22Review 75 min

Sets, functions and cardinality

Review naive set theory, functions and their properties, images and preimages. Develop infinite cardinality and Cantor's diagonal argument, which reappears in the halting problem's undecidability.

After this lesson you can

  • Manipulate set operations, Cartesian products, and power sets and prove identities by double inclusion.
  • Classify functions as injective, surjective, or bijective and reason about composition and inverses.
  • Calculate images and preimages and determine which commute with unions, intersections, and complements.
  • Construct explicit bijections, including Cantor pairing, and prove countability.
  • Apply diagonalization to prove |A| < |P(A)| and that noncomputable functions exist.

Before you start

Motivation: there are more problems than programs

A program is finite text. A property of programs (“this code never writes outside a buffer,” “this function always terminates,” “this model never returns personal data”) is a set of texts: those satisfying it. This lesson ends by proving there are strictly more sets of texts than texts, and therefore strictly more properties than programs able to decide them. Almost all properties, in a sense we will specify, are decided by no program.

This is not merely a logician’s curiosity. It directly affects what you can build:

  • Program analysis. No static-analysis tool can exactly decide a nontrivial property of program behavior: the Rice theorem states this, proven by reduction to the halting problem, whose undecidability is this lesson’s diagonal argument applied to programs. Real tools therefore approximate: they either warn too much (false positives) or miss too much (false negatives); choosing which error to accept is a design decision, not a defect fixed with more engineering.
  • Machine learning. With fixed architecture, a network with pp float32 parameters has only 232p2^{32p} possible parameter values, so represents at most 232p2^{32p} functions. There are 22n2^{2^{n}} Boolean functions of nn input bits. Representing all requires 32p≥2n32p \ge 2^n: with 64-bit inputs, over 5⋅10175 \cdot 10^{17} parameters. This is a finite cardinality argument like this lesson’s, and a fundamental reason learning needs assumptions about the target function.
  • Probability. A random variable is a function X:Ω→RX: \Omega \to \R, and event “XX falls in BB” is set {ω:X(ω)∈B}\{\omega : X(\omega) \in B\}, the preimage of BB. Measure theory rests on an elementary property proven here: preimages preserve unions, intersections, and complements.

We need mathematics’ common language: sets, functions between sets, and a way to compare sizes that works for infinite sets. Much is review, but with a stronger requirement than you may have met before: prove every identity, write every definition with quantifiers, and support every infinity claim with an explicit executable bijection.

Sets

Membership, inclusion, and extensionality

We use naive set theory: a set is a collection of objects, its elements, and only which elements it has matters. Write x∈Ax \in A for “xx belongs to AA.” Sets are equal if they have the same elements, regardless of order or repetition: {1,2,2}={2,1}\{1, 2, 2\} = \{2, 1\}. This is extensionality, written in predicate logic as

A=B  ⟺  ∀x (x∈A↔x∈B).A = B \iff \forall x\,(x \in A \leftrightarrow x \in B).

AA is a subset of BB, A⊆BA \subseteq B, if ∀x (x∈A→x∈B)\forall x\,(x \in A \to x \in B). Extensionality is equivalent to double inclusion: A=BA = B iff A⊆BA \subseteq B and B⊆AB \subseteq A. This is the standard method for proving set equality: take an arbitrary element of one and show it belongs to the other, then reverse.

Do not confuse two relations: ∈\in relates an element to a set, ⊆\subseteq relates two sets. With A={1,{2}}A = \{1, \{2\}\}, 1∈A1 \in A and {2}∈A\{2\} \in A, but 2∉A2 \notin A, {1}⊆A\{1\} \subseteq A, and {2}⊈A\{2\} \not\subseteq A. The empty set ∅\varnothing is a subset of every set (implication x∈∅→x∈Ax \in \varnothing \to x \in A is vacuously true) but not an element of every set: ∅⊆{1}\varnothing \subseteq \{1\} and ∅∉{1}\varnothing \notin \{1\}, whereas ∅∈{∅}\varnothing \in \{\varnothing\}.

Sets are described by enumeration, {2,3,5,7}\{2, 3, 5, 7\}, or comprehension: {x∈A:P(x)}\{x \in A : P(x)\} is the set of elements of AA satisfying formula PP. We use N={0,1,2,… }\N = \{0, 1, 2, \dots\}, including zero as in Python, and Z\Z, Q\Q, R\R with usual meanings.

Operations

The final column is key. Each Boolean set operation is a logical connective applied to “xx belongs”: x∈A∪Bx \in A \cup B means x∈A∨x∈Bx \in A \lor x \in B, and likewise. Expression (A∪B)∖(A∩C)(A \cup B) \setminus (A \cap C) corresponds to formula (a∨b)∧¬(a∧c)(a \lor b) \land \lnot(a \land c), with aa short for x∈Ax \in A. A point xx of the universe “sees” only three bits about the sets, whether it is in AA, BB, and CC, and those bits decide membership in the expression. Points with the same three bits form a Venn diagram region: 23=82^3 = 8, one per truth-table row.

InteractiveSet expressions on Venn diagrams
E1E_1
E1=(A∪B)∖(A∩C)E_1 = (A \cup B) \setminus (A \cap C)
E2E_2
E2=(A∖C)∪(B∖A)E_2 = (A \setminus C) \cup (B \setminus A)
write in E1E_1; | & - ^ and ' for ᶜ also work
E1E_1
ABCU
E2E_2
ABCU
Truth table: one column per region (8 total). 1 means “xx belongs”.
AA
BB
CC
E1E_1
E2E_2
Sets
Regions of E1E_14 of 8
Regions of E2E_24 of 8
E1=E2E_1 = E_2 for every A,B,…A, B, \dots?sí
They highlight the same 4 regions: equality holds for all sets because the logical formulas are equivalent (all 8 rows agree).
Enter two expressions with AA, BB, CC (or DD for four sets) and keyboard symbols. Each illuminates its regions and truth-table row. Are (A∪B)∖(A∩C)(A \cup B) \setminus (A \cap C) and (A∖C)∪(B∖A)(A \setminus C) \cup (B \setminus A) equal? Try the examples: when expressions differ, every red point is a one-element counterexample. Four sets cannot be represented with circles alone; four ellipses produce all 16 regions.

The figure illustrates a theorem worth proving because it makes every set identity a mechanical calculation.

Identities: double inclusion and truth tables

Proof

(2) ⟹ (1). By induction on the expression, x∈Ex \in E iff φE\varphi_E is true under the valuation assigning each letter aia_i the truth value of x∈Aix \in A_i. Equivalent formulas agree under every valuation, so for every x∈Ux \in U, x∈E  ⟺  x∈Fx \in E \iff x \in F; extensionality gives E=FE = F.

(1) ⟹ (2). By contraposition. If φE\varphi_E and φF\varphi_F are not equivalent, some valuation vv makes them differ. Take a one-point universe U={x}U = \{x\} and define Ai={x}A_i = \{x\} if v(ai)v(a_i) is true, otherwise Ai=∅A_i = \varnothing. Then xx lies in vv‘s region, and x∈Ex \in E and x∈Fx \in F have the distinct values of φE\varphi_E and φF\varphi_F under vv: E≠FE \ne F.

(2) ⟺ (3). Regions are exactly valuations, and an expression contains a region iff its formula is true under that valuation.

∎

The proof of (1)⇒(2)(1) \Rightarrow (2) says more: any failed identity already fails in a one-element universe. This is exactly the figure’s counterexample. The theorem also yields a count: an expression is determined by its regions, so nn letters give exactly 22n2^{2^n} distinct expressions up to equality: 256 with three sets and 65,536 with four. They are the same as Boolean functions of nn variables, not coincidentally: they are the same object.

A truth table decides but does not explain. Double inclusion does, and is the format used in texts. Example with a De Morgan law:

Double inclusion stops being a formality when each direction needs a different argument, as soon as functions or infinite quantifiers enter. We will see this with the image of an intersection.

Families, Cartesian products, and power sets

Operations extend to arbitrary families. If (Ai)i∈I(A_i)_{i \in I} is a family indexed by set II, finite or not,

x∈⋃i∈IAi  ⟺  ∃i∈I (x∈Ai),x∈⋂i∈IAi  ⟺  ∀i∈I (x∈Ai).x \in \bigcup_{i \in I} A_i \iff \exists i \in I\ (x \in A_i), \qquad x \in \bigcap_{i \in I} A_i \iff \forall i \in I\ (x \in A_i).

Union is existential quantification and intersection universal, so quantifier laws give generalized De Morgan laws, (⋃iAi)c=⋂iAic\big(\bigcup_i A_i\big)^c = \bigcap_i A_i^c and (⋂iAi)c=⋃iAic\big(\bigcap_i A_i\big)^c = \bigcup_i A_i^c, because ¬∃i P(i)≡∀i ¬P(i)\lnot \exists i\, P(i) \equiv \forall i\, \lnot P(i). For example ⋂n≥1(0,1/n)=∅\bigcap_{n \ge 1} (0, 1/n) = \varnothing: no x>0x > 0 belongs to every interval, since one can take n>1/xn > 1/x. An intersection of a decreasing family of nonempty intervals can be empty, impossible for a finite family.

The Cartesian product A×BA \times B is the set of ordered pairs, and (a,b)=(a′,b′)(a, b) = (a', b') iff a=a′a = a' and b=b′b = b'. For finite AA and BB, ∣A×B∣=∣A∣ ∣B∣\abs{A \times B} = \abs{A}\,\abs{B}, where ∣A∣\abs{A} counts elements. The power set P(A)\mathcal{P}(A) contains all subsets of AA; its elements are sets, where ∈\in and ⊆\subseteq are often confused: S∈P(A)S \in \mathcal{P}(A) means S⊆AS \subseteq A.

Proof

Every subset S⊆AS \subseteq A is determined by indicator 1S:A→{0,1}\ind_S: A \to \{0, 1\}, 1 on elements of SS and 0 elsewhere, and every function A→{0,1}A \to \{0, 1\} indicates exactly one subset: elements where it is 1. There are 2n2^n functions from an nn-element set to {0,1}\{0, 1\} because each element independently chooses its value.

∎

The correspondence S↔1SS \leftrightarrow \ind_S between P(A)\mathcal{P}(A) and {0,1}A\{0, 1\}^A, functions from AA to {0,1}\{0, 1\}, does not require finite AA. With A=NA = \N it identifies subsets of N\N with infinite zero-one sequences, central to diagonalization. This is also how sets are stored as bit masks: integer 0b1011 represents {0,1,3}\{0, 1, 3\}.

Russell’s paradox and why ZFC exists

Unrestricted comprehension, “for each property PP the set {x:P(x)}\{x : P(x)\} exists,” seems harmless but is contradictory. Take property x∉xx \notin x and set R={x:x∉x}R = \{x : x \notin x\}. Then

R∈R  ⟺  R∉R,R \in R \iff R \notin R,

a contradiction. There is no hidden subtlety: this is the same structure as the diagonal argument at the lesson’s end, not by chance.

Mathematics adopted Zermelo–Fraenkel set theory with the axiom of choice, ZFC. We will not develop its axioms, but the idea defusing the paradox: separation allows only {x∈A:P(x)}\{x \in A : P(x)\}, selecting from an existing set AA. Applying Russell’s construction inside AA, RA={x∈A:x∉x}R_A = \{x \in A : x \notin x\}, the same reasoning yields a theorem rather than contradiction: RA∉AR_A \notin A. No set contains all sets, and “the set of all sets” does not exist. Other axioms ensure practical sets exist: pairs, unions, power sets, an infinite set like N\N, and images under definable functions. Everything in this lesson can be formalized in ZFC and, unless stated, without choice.

Functions

Domain, codomain, and image

Two functions are equal if they have the same domain, codomain, and values. Codomain is part of the function even if it seems a detail: x↦x2x \mapsto x^2 from R\R to R\R and x↦x2x \mapsto x^2 from R\R to [0,∞)[0, \infty) have the same values, but only the second is surjective. Programming types behave similarly: a Python function returning a nonnegative int and another annotated -> int doing the same compute alike but promise different things to callers.

Injective, surjective, bijective

Their negations, derived from quantifier laws, give counterexamples: ff is not injective if some x≠x′x \ne x' have f(x)=f(x′)f(x) = f(x'), and not surjective if some y∈Yy \in Y is no element’s image. Examples appearing later:

  • σ(t)=1/(1+e−t)\sigma(t) = 1/(1 + e^{-t}), sigmoid, is a bijection from R\R to (0,1)(0, 1): continuous and strictly increasing, with limits at ∓∞\mp\infty of 0 and 1. Its inverse is logit, log⁡(p/(1−p))\log\big(p/(1-p)\big).
  • Softmax, from RK\R^K to probability vectors with all positive components, is surjective but not injective: softmax⁡(z+c1)=softmax⁡(z)\softmax(\vb{z} + c\vb{1}) = \softmax(\vb{z}) for every c∈Rc \in \R. Classifier logits are therefore determined only up to a constant.
  • A tokenizer satisfying decode(encode(s)) == s for every string ss has injective encode: different texts never receive the same token list. The inverse theorem below guarantees this.
  • A cryptographic hash from arbitrary strings to 256 bits cannot be injective: infinitely many strings and only 22562^{256} digests exist. It is required to make finding two inputs with the same image computationally difficult.

Composition

If f:X→Yf: X \to Y and g:Y→Zg: Y \to Z, composition g∘f:X→Zg \circ f: X \to Z is (g∘f)(x)=g(f(x))(g \circ f)(x) = g(f(x)): ff on the right acts first. It is associative, h∘(g∘f)=(h∘g)∘fh \circ (g \circ f) = (h \circ g) \circ f, because both map xx to h(g(f(x)))h(g(f(x))), and identity idX(x)=x\mathrm{id}_X(x) = x is neutral on both sides.

Proof
  1. If g(f(x))=g(f(x′))g(f(x)) = g(f(x')), injectivity of gg gives f(x)=f(x′)f(x) = f(x'), and of ff gives x=x′x = x'. Conversely, given z∈Zz \in Z some yy has g(y)=zg(y) = z and some xx has f(x)=yf(x) = y, so (g∘f)(x)=z(g \circ f)(x) = z.
  2. If f(x)=f(x′)f(x) = f(x'), applying gg gives (g∘f)(x)=(g∘f)(x′)(g \circ f)(x) = (g \circ f)(x'), and injectivity of g∘fg \circ f gives x=x′x = x'.
  3. Given z∈Zz \in Z, some xx has g(f(x))=zg(f(x)) = z, so y=f(x)y = f(x) satisfies g(y)=zg(y) = z.
∎

The converses of 2 and 3 involving the other function are false; keep a counterexample handy. With X={a}X = \{a\}, Y={1,2}Y = \{1, 2\}, Z={p}Z = \{p\}, f(a)=1f(a) = 1, and g(1)=g(2)=pg(1) = g(2) = p, composition g∘f:{a}→{p}g \circ f: \{a\} \to \{p\} is bijective, but ff is not surjective and gg not injective. Lost information is in YY: ff does not fill it and gg collapses it; g∘fg \circ f sees neither.

Left and right inverses

Proof
  1. If g∘f=idXg \circ f = \mathrm{id}_X, which is injective, the previous theorem makes ff injective. Conversely if ff is injective, each y∈f(X)y \in f(X) has a unique preimage xyx_y. Fix x0∈Xx_0 \in X (using X≠∅X \ne \varnothing) and set g(y)=xyg(y) = x_y if y∈f(X)y \in f(X), otherwise g(y)=x0g(y) = x_0. Then g(f(x))=xg(f(x)) = x for all xx.
  2. If f∘h=idYf \circ h = \mathrm{id}_Y, which is surjective, the previous theorem makes ff surjective. Conversely if ff is surjective, every set f−1({y})f^{-1}(\{y\}) is nonempty, and define h(y)h(y) by choosing one element from each. Then f(h(y))=yf(h(y)) = y.
  3. If g∘f=idXg \circ f = \mathrm{id}_X and f∘h=idYf \circ h = \mathrm{id}_Y, then g=g∘(f∘h)=(g∘f)∘h=hg = g \circ (f \circ h) = (g \circ f) \circ h = h. Parts 1 and 2 give equivalence, and this calculation proves uniqueness: every left inverse equals every right inverse.
∎

The constructions have an important asymmetry. The left inverse is given by a formula. The right inverse chooses a preimage for each yy: if YY is infinite and there is no selection rule, the axiom of choice is needed, and “every surjection has a right inverse” is equivalent to that axiom. The interactive’s finite sets pose no problem, and it counts possible choices.

InteractiveArrows between finite sets
XYfabcd1234
  • arrows from two colliding elements
  • element with no preimage
Fibers f−1({y})f^{-1}(\{y\}): the preimage of each point in YY. Nonempty fibers partition XX.
f−1({1})={b}f^{-1}(\{1\}) = \{b\}
f−1({2})={a,c}f^{-1}(\{2\}) = \{a, c\}
f−1({3})=∅f^{-1}(\{3\}) = \varnothing
f−1({4})={d}f^{-1}(\{4\}) = \{d\}
Injective: no fiber contains two elements. Surjective: none is empty. Right inverses: the product of fiber sizes.
Mode
Sizes
4
4
Inverse
Injective?no
Surjective?no
Bijective?no
Functions X→YX \to Y256
of which injective24
of which surjective24
f(a)=f(c)=2f(a) = f(c) = 2: not injective. 3 has no preimage: not surjective.
Drag each arrow from an element of XX to its new image, or tap the element to advance. Red arrows collide (not injective), and dashed amber nodes receive none (not surjective). Request a left or right inverse: when does one exist, and how many? In ‘Composition,’ drag ff and gg, choose a claim, and search all possible pairs (f,g)(f, g) of those sizes for a counterexample.

For finite sets the count is exact. If ∣X∣=m\abs{X} = m and ∣Y∣=n\abs{Y} = n, there are nmn^m functions X→YX \to Y; injective ones number n(n−1)⋯(n−m+1)n(n-1)\cdots(n-m+1), since each element of XX chooses an unused image, and the product is 0 if m>nm > n. This is the pigeonhole principle: with more pigeons than holes, two share one. If also m=nm = n, a function between finite sets of equal size is injective iff surjective, because its image has nn elements exactly when no collisions occur. This equivalence, often used automatically in linear algebra and combinatorics, is false for infinite sets: n↦n+1n \mapsto n + 1 is injective from N\N to N\N and not surjective since nothing maps to 0. This is the first sign infinity behaves differently.

Image and preimage

Preimage exists for any function, invertible or not: f−1(B)f^{-1}(B) is a set, not application of a function f−1f^{-1}. For f(x)=x2f(x) = x^2 on R\R, f−1({4})={−2,2}f^{-1}(\{4\}) = \{-2, 2\}, f−1([0,9])=[−3,3]f^{-1}([0, 9]) = [-3, 3], and f−1({−1})=∅f^{-1}(\{-1\}) = \varnothing. When ff is bijective, the preimage of BB under ff equals the image of BB under its inverse function, so notation causes no issue. Sets f−1({y})f^{-1}(\{y\}) are fibers of ff; distinct yy fibers are disjoint and their union is XX, so nonempty fibers partition the domain. A classifier’s fibers f−1({k})f^{-1}(\{k\}) are decision regions.

Proof

Every preimage identity is a chain of equivalences. For union,

x∈f−1(⋃iBi)  ⟺  f(x)∈⋃iBi  ⟺  ∃i (f(x)∈Bi)  ⟺  ∃i (x∈f−1(Bi))  ⟺  x∈⋃if−1(Bi).x \in f^{-1}\Big(\bigcup_i B_i\Big) \iff f(x) \in \bigcup_i B_i \iff \exists i\ \big(f(x) \in B_i\big) \iff \exists i\ \big(x \in f^{-1}(B_i)\big) \iff x \in \bigcup_i f^{-1}(B_i).

Intersection and complement are analogous with ∀\forall and ¬\lnot; complete them in the exercises. For image of a union, y∈f(⋃iAi)y \in f(\bigcup_i A_i) iff some xx in some AiA_i has f(x)=yf(x) = y, iff some ii has y∈f(Ai)y \in f(A_i): existential quantifiers commute. For intersection, “there exists xx in every AiA_i” implies “for each ii some xx is in AiA_i,” but the converse fails because xx can depend on ii: with f(x)=x2f(x) = x^2, A1={−1}A_1 = \{-1\}, and A2={1}A_2 = \{1\}, f(A1∩A2)=∅f(A_1 \cap A_2) = \varnothing whereas f(A1)∩f(A2)={1}f(A_1) \cap f(A_2) = \{1\}. Characterization by injectivity is the first guided exercise.

∎

The two theorem columns have a simple interpretation: preimage asks something about f(x)f(x) for each domain point xx, and any logical connective passes inside unchanged. Image hides an existential quantifier, “some xx has f(x)=yf(x) = y,” which commutes with ∃\exists and ∨\lor, but not ∀\forall, ∧\land, or ¬\lnot.

ProofImage of an intersection
Prove: For every f:X→Yf: X \to Y and all A,B⊆XA, B \subseteq X, f(A∩B)⊆f(A)∩f(B)f(A \cap B) \subseteq f(A) \cap f(B). Equality holds for all AA and BB iff ff is injective.
0
Recall y∈f(A)y \in f(A) means some x∈Ax \in A has f(x)=yf(x) = y.

Step 1 of 4. For inclusion, let y∈f(A∩B)y \in f(A \cap B). What do you know?

ProofPreimage commutes with everything
Prove: For every f:X→Yf: X \to Y, family (Bi)i∈I(B_i)_{i \in I} of subsets of YY, and B⊆YB \subseteq Y: f−1(⋂iBi)=⋂if−1(Bi)f^{-1}\big(\bigcap_i B_i\big) = \bigcap_i f^{-1}(B_i) and f−1(Y∖B)=X∖f−1(B)f^{-1}(Y \setminus B) = X \setminus f^{-1}(B).
0
Prove each equality by a chain of equivalences starting with arbitrary x∈Xx \in X.

Step 1 of 3. x∈f−1(⋂iBi)x \in f^{-1}\big(\bigcap_i B_i\big) is equivalent to...

Cardinality

Equinumerosity

For finite sets “having the same number of elements” means pairing them one to one; that idea, not counting, generalizes.

Equinumerosity is reflexive (identity), symmetric (a bijection’s inverse is a bijection), and transitive (composition of bijections): an equivalence relation. For finite sets it coincides with equal element counts. For infinite sets it immediately contradicts intuition about parts and wholes:

  • N\N and the evens. n↦2nn \mapsto 2n is a bijection from N\N to 2N={0,2,4,… }2\N = \{0, 2, 4, \dots\}. An infinite set can be equinumerous with a proper subset; in fact a set is infinite iff this happens (with choice). Galileo observed it for perfect squares in 1638 and took it as evidence that “greater,” “less,” and “equal” do not apply to infinite quantities. Cantor defined “same size” by one-to-one correspondence; Dedekind (1888) turned the paradox into a definition of infinite set.
  • N\N and Z\Z. Mapping n↦2nn \mapsto 2n for n≥0n \ge 0 and n↦−2n−1n \mapsto -2n - 1 for n<0n < 0 is a bijection from Z\Z to N\N: nonnegatives go to evens, negatives to odds.
  • R\R and (0,1)(0, 1). Sigmoid is a bijection from R\R to (0,1)(0, 1). A bounded interval has as many points as the entire line.
  • (0,1)(0, 1) and [0,1][0, 1]. Adding two points changes nothing. The function mapping 0↦120 \mapsto \tfrac{1}{2}, 1↦131 \mapsto \tfrac{1}{3}, 1n↦1n+2\tfrac{1}{n} \mapsto \tfrac{1}{n+2} for n≥2n \ge 2, and fixing other points is a bijection from [0,1][0, 1] to (0,1)(0, 1): it shifts sequence 0,1,12,13,…0, 1, \tfrac12, \tfrac13, \dots two places to make room, as in Hilbert’s hotel.

For the last two, finding a bijection needs ingenuity; others are harder. The next theorem avoids this: two injections, one each way, usually easy, suffice.

Proof

Sketch. Assume AA and BB disjoint (otherwise replace them with disjoint copies). For each element trace its ancestor chain backward: if a∈Aa \in A is in gg‘s image, its parent is the unique bb with g(b)=ag(b) = a; if that bb is in ff‘s image, its parent is the unique a′a' with f(a′)=bf(a') = b, and so on. Injectivity ensures at most one parent per element. Each backward chain either stops at a parentless element of AA, stops at one of BB, or never stops. This partitions AA into AAA_A, ABA_B, and A∞A_\infty according to chain origin, and likewise BB.

ff maps AAA_A bijectively to BAB_A: applying ff adds a link without changing origin, and every element of BAB_A has a parent in AAA_A because its chain does not stop there. Likewise ff maps A∞A_\infty bijectively to B∞B_\infty, and gg maps BBB_B bijectively to ABA_B. Define h(a)=f(a)h(a) = f(a) if a∈AA∪A∞a \in A_A \cup A_\infty and h(a)=g−1(a)h(a) = g^{-1}(a) if a∈ABa \in A_B, where g−1(a)g^{-1}(a) is the existing parent of aa. The three pieces biject classes partitioning AA and BB, so hh is bijective. The construction is explicit and uses no choice.

∎

The theorem makes ∣[0,1]∣=∣(0,1)∣\abs{[0, 1]} = \abs{(0, 1)} immediate: inclusion (0,1)→[0,1](0, 1) \to [0, 1] is injective and x↦(x+1)/3x \mapsto (x + 1)/3 maps [0,1][0, 1] injectively into [1/3,2/3]⊆(0,1)[1/3, 2/3] \subseteq (0, 1). A deeper use needed later is ∣R∣=∣P(N)∣\abs{\R} = \abs{\mathcal{P}(\N)}:

  • P(N)→[0,1]\mathcal{P}(\N) \to [0, 1], S↦∑i∈S2⋅3−(i+1)S \mapsto \sum_{i \in S} 2 \cdot 3^{-(i+1)}, is injective: its ternary digits are 2 at positions in SS and 0 elsewhere, and a ternary expansion using only zeros and twos is unique.
  • (0,1)→P(N)(0, 1) \to \mathcal{P}(\N) mapping xx to positions of ones in its binary expansion not ending in infinitely many ones is injective because that expansion exists uniquely.

With sigmoid, ∣R∣=∣(0,1)∣≤∣P(N)∣≤∣[0,1]∣=∣R∣\abs{\R} = \abs{(0, 1)} \le \abs{\mathcal{P}(\N)} \le \abs{[0, 1]} = \abs{\R}. The cardinality of R\R is the continuum, c\mathfrak{c}, and we have shown c=∣P(N)∣=∣{0,1}N∣\mathfrak{c} = \abs{\mathcal{P}(\N)} = \abs{\{0, 1\}^{\N}}.

Countability

The stated equivalence needs a lemma: every infinite subset S⊆NS \subseteq \N is equinumerous with N\N, because listing elements in increasing order s0<s1<s2<⋯s_0 < s_1 < s_2 < \cdots gives bijection n↦snn \mapsto s_n. If AA injects into N\N, it is equinumerous with its image, finite or infinite and then equinumerous with N\N. For nonempty AA, countability is also equivalent to a surjection N→A\N \to A, an enumeration a0,a1,a2,…a_0, a_1, a_2, \dots in which every element appears at least once; no choice is needed: given a surjection, a↦min⁡{n:an=a}a \mapsto \min\{n : a_n = a\} is an injection. Enumeration with repetition suffices to prove countability and is what we use.

The natural-number plane: Cantor pairing

The first surprise is N×N\N \times \N is no larger than N\N. Place pairs on an infinite grid. Traversing rows fails because the first never ends. Diagonals work: diagonal x+y=wx + y = w has w+1w + 1 cells, all diagonals are finite, and every cell lies on one. Diagonals before ww have 1+2+⋯+w=Tw=w(w+1)21 + 2 + \cdots + w = T_w = \tfrac{w(w+1)}{2} cells total, the wwth triangular number. Numbering each diagonal bottom up gives cell (x,y)(x, y) the number

π(x,y)=Tx+y+y=(x+y)(x+y+1)2+y.\pi(x, y) = T_{x+y} + y = \frac{(x+y)(x+y+1)}{2} + y.
Proof

For each ww, π\pi values on diagonal x+y=wx + y = w are Tw,Tw+1,…,Tw+wT_w, T_w + 1, \dots, T_w + w, exactly integers in [Tw,Tw+1)[T_w, T_{w+1}), because Tw+1=Tw+w+1T_{w+1} = T_w + w + 1. These intervals are disjoint and cover N\N, so each nn lies in exactly one and has exactly one preimage there: π\pi is bijective. The inverse formula finds ww, the largest with Tw≤nT_w \le n; the derivation follows.

∎
Tw≤n  ⟺  w2+w−2n≤0T_w \le n \iff w^2 + w - 2n \le 0
We seek the largest natural ww with Tw≤nT_w \le n; multiply Tw=w(w+1)/2≤nT_w = w(w+1)/2 \le n by 2.
1/5

The derivation’s last step is not technical trivia. If 8n+1\sqrt{8n + 1} is computed in floating point with 53 mantissa bits, 8n+18n + 1 ceases to be exactly representable above 253≈9⋅10152^{53} \approx 9 \cdot 10^{15}, and near a perfect square rounding may cross an integer. The interactive gives an example: for n=π(0,227−1)=9 007 199 321 849 855n = \pi(0, 2^{27} - 1) = 9\,007\,199\,321\,849\,855, the naive version returns (134 217 729,−1)(134\,217\,729, -1), a pair with a negative coordinate.

InteractiveCantor's zigzag
013610152128247111622293758121723303847913182431394858141925324049597020263341506071832734425161728497354352627385981120011223344556677xy
complete
  • diagonal traversal
  • jump to next diagonal
  • selected cell and its diagonal
Cells
π(3,4)=T7⏟28+4=32\pi(3, 4) = \underbrace{T_{7}}_{28} + 4 = 32
diagonal w=x+yw = x + y7
(x,y)(x, y) with integer square root(3, 4)
(x,y)(x, y) with floating-point sqrt(3, 4)
Both inverses agree. Tw=w(w+1)/2T_w = w(w+1)/2 counts cells on previous diagonals, and yy is the position within diagonal ww.
Cells of N×N\N \times \N are numbered diagonal by diagonal; play to see the traversal. Tap a cell to see π(x,y)=Tx+y+y\pi(x, y) = T_{x+y} + y, or enter a number up to 60 digits to find its cell with an exact integer square root. Press ‘≈ 9·10¹⁵’ and compare integer and floating-point roots. In ‘Fractions,’ cell (p,q)(p, q) is p/qp/q and unreduced fractions are skipped: an enumeration of positive rationals.

Unions, rationals, strings, and programs

Pairing makes almost everything built from finite pieces countable.

Proof
  1. If α:A→N\alpha: A \to \N and β:B→N\beta: B \to \N are injections, (a,b)↦π(α(a),β(b))(a, b) \mapsto \pi(\alpha(a), \beta(b)) is injective.
  2. Let A0,A1,…A_0, A_1, \dots be countable and nonempty (empty sets contribute nothing), and choose a surjection ei:N→Aie_i: \N \to A_i for each ii. Then n↦ex(y)n \mapsto e_x(y), with (x,y)=π−1(n)(x, y) = \pi^{-1}(n), surjects from N\N to ⋃iAi\bigcup_i A_i. Choosing infinitely many enumerations at once uses a weak form of choice (countable choice); in this lesson’s concrete cases enumerations have formulas, so it is unnecessary.
  3. Z\Z follows from the previous bijection. Q\Q is the image of Z×(N∖{0})\Z \times (\N \setminus \{0\}) under (p,q)↦p/q(p, q) \mapsto p/q, a surjection from a countable set.
  4. Σ∗=⋃n≥0Σn\Sigma^* = \bigcup_{n \ge 0} \Sigma^n, and every Σn\Sigma^n is countable by point 1. A Python program is a finite byte string, so programs are a subset of Σ∗\Sigma^* for Σ={0,…,255}\Sigma = \{0, \dots, 255\}.
  5. S↦∑i∈S2iS \mapsto \sum_{i \in S} 2^i bijects finite subsets of N\N and N\N: binary notation.
∎

Binary strings have an elegant explicit bijection, shortlex order: length first, then lexicographic order at equal length, ε,0,1,00,01,10,11,000,…\varepsilon, 0, 1, 00, 01, 10, 11, 000, \dots String number nn is obtained by writing n+1n + 1 in binary and removing the leading 1. Shortlex similarly enumerates strings over any finite alphabet of kk symbols (with bijective base-kk numeration); in the lab you will program it to assign print('hola') its natural number.

We now know algebraic numbers are countable (roots of integer-coefficient polynomials: countably many polynomials, each with finitely many roots) and so are computable reals, those xx for which a program given kk returns a rational within 2−k2^{-k} of xx: there are at most as many as programs. Every constant you have calculated, π\pi, ee, 2\sqrt 2, Euler’s constant, is computable. Are all reals computable, or is R\R countable?

The diagonal argument

Proof

Let s0,s1,s2,…s_0, s_1, s_2, \dots be any sequence of elements of {0,1}N\{0, 1\}^{\N}. Define sequence dd by

d(k)=1−sk(k),k∈N.d(k) = 1 - s_k(k), \qquad k \in \N.

For each kk, d(k)≠sk(k)d(k) \ne s_k(k), so d≠skd \ne s_k: dd differs from the kkth sequence at position kk. Thus dd does not appear in the list, and no sequence of elements of {0,1}N\{0, 1\}^{\N} enumerates them all. No surjection N→{0,1}N\N \to \{0, 1\}^{\N} exists.

∎

This construction is Cantor’s diagonal argument. Its strength is quantifier order: it does not say one particular list is incomplete, but that for every list a missing sequence exists, and it gives a way to construct one from that list. Any attempt to repair the list by adding missing dd creates a new list with its own diagonal.

InteractiveThe diagonal that always escapes
i
0
1
2
3
4
5
6
7
8
9
10
11
description
…
all zeros
…
alternates 1, 0
…
1 at primes
…
all ones
…
1 at powers of 2
…
1 at squares
…
1 at multiples of 3
…
bits of π
⋮
⋮
⋮
⋮
⋮
dd
1
1
0
0
0
1
0
1
0
0
0
0
…
dk=1−sk(k)d_k = 1 - s_k(k)
complete
  • list bit 1
  • diagonal and its flip
0
Patches applied0
Is d$ in the list?no
dversuss3 versus s_{3} at position 30 ≠ 1
The flipped diagonal dk=1−sk(k)d_k = 1 - s_k(k) differs from each row sks_k at least in position kk.
Each row is an infinite binary sequence in a supposedly complete list. Play: invert the diagonal position by position to construct dd, differing from sks_k at position kk. Insert dd into any row and watch the new diagonal escape again. Tap cells to edit the list: only diagonal changes affect dd. With ‘All with finitely many ones,’ the list contains every sequence with finitely many ones and the diagonal has infinitely many.
Proof

We already know from ∣[0,1]∣=∣{0,1}N∣\abs{[0, 1]} = \abs{\{0, 1\}^{\N}}, but the direct decimal argument is instructive. Let x0,x1,…x_0, x_1, \dots list numbers in [0,1][0, 1], each with decimal expansion xk=0.ak0ak1ak2…x_k = 0.a_{k0}a_{k1}a_{k2}\ldots. Define y=0.b0b1b2…y = 0.b_0 b_1 b_2 \ldots with bk=5b_k = 5 if akk≠5a_{kk} \ne 5 and bk=4b_k = 4 if akk=5a_{kk} = 5. The expansion of yy contains neither zeros nor nines, hence is the unique decimal expansion of yy, and differs from xkx_k at digit kk. Thus y≠xky \ne x_k for every kk.

∎

The 0-and-9 precaution is not pedantry: 0.4999…=0.5000…0.4999\ldots = 0.5000\ldots, so a diagonal merely changing digits could build another expansion of the same number. Choosing 4 and 5 avoids this. The argument proves much: computable reals are countable, so almost all reals are not computable, meaning their complement is countable and R\R is not. Some can be precisely defined, such as the real whose binary digit nn is 1 iff the nnth program halts, but none can have arbitrarily many digits computed by a program: that would make it computable.

Cantor’s theorem

The argument does not depend on bit-sequence rows. Reading each sequence as the subset of N\N where it is 1, the inverted diagonal is set {k:k∉Sk}\{k : k \notin S_k\}, and the construction works over any set.

Proof

a↦{a}a \mapsto \{a\} injects A→P(A)A \to \mathcal{P}(A), so ∣A∣≤∣P(A)∣\abs{A} \le \abs{\mathcal{P}(A)}. It remains to show no bijection exists, for which it suffices that no f:A→P(A)f: A \to \mathcal{P}(A) is surjective. Given ff, consider the diagonal set

D={a∈A:a∉f(a)}⊆A.D = \{a \in A : a \notin f(a)\} \subseteq A.

If D=f(m)D = f(m) for some m∈Am \in A, then m∈D  ⟺  m∉f(m)  ⟺  m∉Dm \in D \iff m \notin f(m) \iff m \notin D, a contradiction. Thus DD is not in ff‘s image.

∎

This is Russell’s paradox turned into a theorem: R={x:x∉x}R = \{x : x \notin x\} gave contradiction there; the same trick applied inside a set shows a particular object cannot exist here. Consequences are far-reaching. Chain ∣N∣<∣P(N)∣<∣P(P(N))∣<⋯\abs{\N} < \abs{\mathcal{P}(\N)} < \abs{\mathcal{P}(\mathcal{P}(\N))} < \cdots never ends: infinitely many sizes of infinity exist and none is greatest. The set of all sets VV cannot exist because it would contain P(V)\mathcal{P}(V) as a subset and thus ∣P(V)∣≤∣V∣\abs{\mathcal{P}(V)} \le \abs{V}.

ProofNo surjection from A to its power set
Prove: For every set AA and function f:A→P(A)f: A \to \mathcal{P}(A), ff is not surjective.
0
Exhibit a subset of AA that is not f(a)f(a) for any aa.

Step 1 of 3. Which subset do you propose?

Functions no program computes

Join both halves. Programs are countable because they are finite strings. Functions N→{0,1}\N \to \{0, 1\} form {0,1}N\{0, 1\}^{\N}, uncountable. Each program computes at most one function, so the vast majority of functions N→{0,1}\N \to \{0, 1\} are computed by no program. Equivalently, a subset of N\N is a function N→{0,1}\N \to \{0, 1\}, so most decision problems on natural numbers (or programs numbered as above) are undecidable.

The cardinality argument proves existence without identifying one. To obtain a concrete one, diagonalize over the programs themselves. Number all programs P0,P1,P2,…P_0, P_1, P_2, \dots, and suppose a program HH decides, given nn and kk, whether PnP_n halts on input kk. Then the program

D(n)={1−Pn(n)if Pn halts on input n and returns 0 or 1,0otherwiseD(n) = \begin{cases} 1 - P_n(n) & \text{if } P_n \text{ halts on input } n \text{ and returns 0 or 1,} \\ 0 & \text{otherwise} \end{cases}

could be written using HH, would always terminate, and would be one of the listed programs, say PmP_m. But then D(m)=1−Pm(m)=1−D(m)D(m) = 1 - P_m(m) = 1 - D(m), a contradiction. Thus HH does not exist: the halting problem is undecidable, proven in detail in the computability lesson. The pattern matches the figure: rows are programs, with a diagonal and inversion. The only addition is that making the construction a program requires computing the diagonal, exactly what cannot be done.

Implementation: executable bijections and diagonals

All this fits in a few Python functions with exact integers. Start with the identity theorem: to decide a set identity, evaluate it in the “free model,” where each set is the set of Venn regions it contains. If it fails, differing regions are one-element counterexamples.

[ ]Set identities: the region modelBrowser
from itertools import product

def regiones(n):
    """Las 2^n regiones del diagrama de Venn de n conjuntos: cada una es un vector de pertenencias."""
    return list(product((0, 1), repeat=n))

def modelo_libre(n):
    """Los conjuntos A_1..A_n, cada uno como el conjunto de las regiones que lo contienen, y el universo."""
    R = regiones(n)
    return [frozenset(r for r in R if r[i]) for i in range(n)], frozenset(R)

def identidad(lhs, rhs, n=3):
    """¿lhs = rhs para TODOS los conjuntos? Por el teorema, basta mirar el modelo de las regiones."""
    S, U = modelo_libre(n)
    a, b = lhs(*S, U), rhs(*S, U)
    return a == b, sorted(a ^ b)          # regiones donde difieren: cada una es un contraejemplo

casos = {   # | unión, & intersección, - diferencia, ^ diferencia simétrica, U - X complemento
    "(A ∪ B) ∖ (A ∩ C) = (A ∖ C) ∪ (B ∖ A)": (lambda A, B, C, U: (A | B) - (A & C), lambda A, B, C, U: (A - C) | (B - A)),
    "(A ∪ B)ᶜ = Aᶜ ∩ Bᶜ":                    (lambda A, B, C, U: U - (A | B),       lambda A, B, C, U: (U - A) & (U - B)),
    "A ∩ (B ∪ C) = (A ∩ B) ∪ (A ∩ C)":       (lambda A, B, C, U: A & (B | C),       lambda A, B, C, U: (A & B) | (A & C)),
    "(A △ B) △ C = A △ (B △ C)":             (lambda A, B, C, U: (A ^ B) ^ C,       lambda A, B, C, U: A ^ (B ^ C)),
    "A ∖ (B ∖ C) = (A ∖ B) ∖ C":             (lambda A, B, C, U: A - (B - C),       lambda A, B, C, U: (A - B) - C),
    "(A ∪ B) ∖ B = A":                       (lambda A, B, C, U: (A | B) - B,       lambda A, B, C, U: A),
}
for nombre, (l, r) in casos.items():
    ok, dif = identidad(l, r)
    print(f"{nombre:40s} {'vale' if ok else 'falla en las regiones ' + str(dif)}")

Regions read as (x∈A,x∈B,x∈C)(x \in A, x \in B, x \in C): difference associativity fails at (1,0,1)(1, 0, 1) and (1,1,1)(1, 1, 1), points of A∩CA \cap C. The theorem says examining this model loses nothing. Check conversely with 2000 triples of random subsets of a 12-element universe:

[ ]The free model does not lieBrowser
import random

random.seed(0)
U12 = frozenset(range(12))

def al_azar():
    return frozenset(x for x in U12 if random.random() < 0.5)

ternas = [(al_azar(), al_azar(), al_azar()) for _ in range(2000)]
for nombre, (l, r) in casos.items():
    fallos = sum(l(A, B, C, U12) != r(A, B, C, U12) for A, B, C in ternas)
    print(f"{nombre:40s} falla en {fallos:4d} de 2000 ternas al azar")

Valid identities never fail, and false ones almost always fail: one of 12 elements merely needs to land in either bad region. Now finite-set functions. Represent f:{0,…,m−1}→{0,…,n−1}f: \{0, \dots, m-1\} \to \{0, \dots, n-1\} by its image tuple, count injections and surjections by brute force, and compare with formulas: n(n−1)⋯(n−m+1)n(n-1)\cdots(n-m+1) for injections and inclusion–exclusion ∑k=0n(−1)k(nk)(n−k)m\sum_{k=0}^{n} (-1)^k \binom{n}{k}(n-k)^m for surjections, subtracting functions missing an element.

[ ]Finite functions: counting and compositionBrowser
from math import comb, perm

def funciones(m, n):
    """Todas las funciones de {0..m-1} en {0..n-1}, como tuplas de imágenes."""
    return list(product(range(n), repeat=m))

def es_inyectiva(f):
    return len(set(f)) == len(f)

def es_sobreyectiva(f, n):
    return set(f) == set(range(n))

def sobreyecciones(m, n):
    return sum((-1) ** k * comb(n, k) * (n - k) ** m for k in range(n + 1))

print(" m  n  funciones  inyectivas  sobreyectivas")
for m, n in [(3, 3), (3, 5), (4, 3), (5, 5), (6, 3)]:
    F = funciones(m, n)
    iny = sum(map(es_inyectiva, F))
    sob = sum(es_sobreyectiva(f, n) for f in F)
    assert iny == perm(n, m) and sob == sobreyecciones(m, n)    # math.perm(n, m) = 0 si m > n
    print(f"{m:2d} {n:2d} {len(F):10d} {iny:11d} {sob:14d}")

def compon(g, f):
    return tuple(g[y] for y in f)

def contraejemplos(hip, concl, tam=3):
    """Parejas (f, g), con todos los tamaños hasta tam, que cumplen la hipótesis y no la conclusión."""
    total = malos = 0
    for m, n, p in product(range(1, tam + 1), repeat=3):
        for f in funciones(m, n):
            for g in funciones(n, p):
                total += 1
                malos += hip(f, g, n, p) and not concl(f, g, n, p)
    return malos, total

afirmaciones = {
    "g∘f inyectiva ⇒ f inyectiva":       (lambda f, g, n, p: es_inyectiva(compon(g, f)), lambda f, g, n, p: es_inyectiva(f)),
    "g∘f inyectiva ⇒ g inyectiva":       (lambda f, g, n, p: es_inyectiva(compon(g, f)), lambda f, g, n, p: es_inyectiva(g)),
    "g∘f sobreyectiva ⇒ g sobreyectiva": (lambda f, g, n, p: es_sobreyectiva(compon(g, f), p), lambda f, g, n, p: es_sobreyectiva(g, p)),
    "g∘f sobreyectiva ⇒ f sobreyectiva": (lambda f, g, n, p: es_sobreyectiva(compon(g, f), p), lambda f, g, n, p: es_sobreyectiva(f, n)),
}
for nombre, (h, c) in afirmaciones.items():
    malos, total = contraejemplos(h, c)
    print(f"{nombre:35s} contraejemplos: {malos:5d} de {total}")

The two theorem claims have no counterexample among all pairs (f,g)(f, g) on sets up to three elements; the other two have 198 and 135 of 1618 pairs. Move to infinity. Cantor pairing and its inverse in exact integer arithmetic with math.isqrt, which computes ⌊m⌋\lfloor\sqrt{m}\rfloor for arbitrarily large integers without floating point:

[ ]Cantor pairing and its exact inverseBrowser
import math

def pair(x, y):
    return (x + y) * (x + y + 1) // 2 + y

def unpair(n):
    w = (math.isqrt(8 * n + 1) - 1) // 2      # mayor w con T_w <= n, sin coma flotante
    y = n - w * (w + 1) // 2
    return w - y, y

N = 200_000
assert all(pair(*unpair(n)) == n for n in range(N))                      # π ∘ π⁻¹ = id en [0, N)
celdas = [(x, w - x) for w in range(400) for x in range(w + 1)]          # diagonales x + y < 400
assert sorted(pair(x, y) for x, y in celdas) == list(range(len(celdas)))  # ocupan exactamente [0, T_400)
assert all(unpair(pair(x, y)) == (x, y) for x, y in celdas)
print("π(3, 4) =", pair(3, 4), "   π⁻¹(100) =", unpair(100), "   π⁻¹(10⁶) =", unpair(10**6))

def unpair_float(n):
    w = int((math.sqrt(8 * n + 1) - 1) // 2)  # la versión ingenua
    y = n - w * (w + 1) // 2
    return w - y, y

n = pair(0, 2**27 - 1)
print(f"n = {n}:  exacta {unpair(n)},  coma flotante {unpair_float(n)}")
print("enteros enormes sin problema:", unpair(pair(10**40, 7)) == (10**40, 7))

Exhaustive checking is the honest way to test a bijection in code: it proves nothing outside the range, but any one-step error appears quickly. Floating-point failure, conversely, never appears in any small range: the first nn of form Tw−1T_w - 1 where it fails is exactly the cell’s, with w=227w = 2^{27}. Reason about precision rather than trusting tests.

Finite strings. The shortlex bijection from N\N to binary strings and its byte generalization, bijective base-256 numeration, gives every program its number:

[ ]Finite strings and programs: explicit numberingBrowser
from itertools import count, islice

def cadena(n):
    """n-ésima cadena binaria en orden shortlex: n + 1 en binario sin el 1 inicial."""
    return bin(n + 1)[3:]

def indice(s):
    return int("1" + s, 2) - 1

print([cadena(n) for n in range(15)])
assert all(indice(cadena(n)) == n for n in range(100_000))

def shortlex():
    """Todas las cadenas binarias: por longitud y, dentro de cada longitud, en orden lexicográfico."""
    for L in count(0):
        for t in product("01", repeat=L):
            yield "".join(t)

assert list(islice(shortlex(), 2**12 - 1)) == [cadena(n) for n in range(2**12 - 1)]

def indice_bytes(b: bytes) -> int:
    """Numeración biyectiva en base 256: la cadena vacía es 0 y el orden es shortlex."""
    k = 0
    for byte in b:
        k = 256 * k + byte + 1
    return k

def bytes_de(k: int) -> bytes:
    out = bytearray()
    while k > 0:
        k, r = divmod(k - 1, 256)
        out.append(r)
    return bytes(reversed(out))

assert all(indice_bytes(bytes_de(k)) == k for k in range(70_000))
programa = "print('hola')"
k = indice_bytes(programa.encode("utf-8"))
print(f"{programa!r} es el programa número {k} ({len(str(k))} cifras)")
print("y el número k vuelve a ser el programa:", bytes_de(k).decode("utf-8"))

Every Python program occupies a place in this list alongside byte strings that are not valid programs. Finally diagonalization. Function diagonal receives any enumerator, a function returning the nnth sequence as a Python function given nn, and returns a sequence not in the list. Test three enumerators: all sequences with finitely many ones, all periodic ones, and a pseudorandom list.

[ ]The diagonal against any enumeratorBrowser
import matplotlib.pyplot as plt
import numpy as np
from itertools import combinations

def diagonal(enum):
    """enum(n) es la n-ésima sucesión (una función i -> 0 o 1). La diagonal difiere de todas."""
    return lambda i: 1 - enum(i)(i)

def primeros(s, k=36):
    return "".join(str(s(i)) for i in range(k))

finitos = lambda n: (lambda i: (n >> i) & 1)                               # n en binario, al revés
periodicas = lambda n: (lambda i, p=cadena(n + 1): int(p[i % len(p)]))     # el patrón n-ésimo, repetido
aleatorias = lambda n: (lambda i: random.Random(1009 * n + i).getrandbits(1))

for nombre, enum in [("finitos unos", finitos), ("periódicas", periodicas), ("aleatorias", aleatorias)]:
    d = diagonal(enum)
    assert all(d(k) != enum(k)(k) for k in range(3000))
    print(f"{nombre:13s} d = {primeros(d)}...")

# el teorema de Cantor, exhaustivo en un conjunto pequeño: todas las f: A -> P(A) con |A| = 3
A = range(3)
partes = [frozenset(c) for r in range(4) for c in combinations(A, r)]
for imagenes in product(partes, repeat=3):                                 # 8³ = 512 funciones
    D = frozenset(a for a in A if a not in imagenes[a])
    assert D not in imagenes
print(f"{len(partes) ** 3} funciones A -> P(A): ninguna tiene el conjunto diagonal en su imagen")

K = 16
T = np.array([[periodicas(n)(i) for i in range(K)] for n in range(K)])
fig, ax = plt.subplots(figsize=(6.2, 4.4))
ax.imshow(np.vstack([T, np.full((1, K), np.nan), [[diagonal(periodicas)(i) for i in range(K)]]]), cmap="Blues", vmin=-0.4, vmax=1.4)
ax.plot(range(K), range(K), "s", ms=11, mfc="none", mec="C3", mew=1.6)
ax.set_yticks(list(range(K)) + [K + 1], [f"s{n}" for n in range(K)] + ["d"])
ax.set_xticks(range(K)); ax.set_title("Sucesiones periódicas y su diagonal invertida")
plt.tight_layout()
plt.show()

All three diagonals differ from every row, as the proof guarantees. The first is 111…111\ldots, the infinite-ones sequence absent from the finite-ones list. The second is not periodic and cannot be, because the list includes every periodic pattern. The final output line checks Cantor’s theorem over all functions in a small case.

The professional version

Python set data structures implement this lesson’s operations, with a trap: set is mutable and cannot be placed inside another set; for sets of sets such as P(A)\mathcal{P}(A) use frozenset. Operators distinguish ∈\in from ⊆\subseteq as on paper: x in S is membership, S <= T inclusion.

[ ]Sets of sets: membership versus inclusionBrowser
A = frozenset({1, 2})
P = {frozenset(c) for r in range(3) for c in combinations(A, r)}   # P(A), un conjunto de frozensets
print(sorted(map(sorted, P)))
print("{1} ∈ P(A):", frozenset({1}) in P, "   {1} ⊆ A:", {1} <= A, "   {1} ⊆ P(A):", frozenset({1}) <= P)
print("∅ ∈ P(A) y ∅ ⊆ P(A):", frozenset() in P, frozenset() <= P)
try:
    {{1, 2}}
except TypeError as e:
    print("un set dentro de un set:", e)

frozenset({1}) <= P asks whether element 1 is in P, and it is not: P’s elements are sets. To decide identities symbolically, SymPy translates to logic, exactly as the identity theorem: the identity holds iff formula “both sides differ” is unsatisfiable.

[ ]SymPy: identities by satisfiabilityBrowser
from sympy import symbols
from sympy.logic.boolalg import And, Or, Not, Xor
from sympy.logic.inference import satisfiable

a, b, c = symbols("a b c")                            # a significa «x ∈ A»
lhs = And(Or(a, b), Not(And(a, c)))                   # x ∈ (A ∪ B) ∖ (A ∩ C)
rhs = Or(And(a, Not(c)), And(b, Not(a)))              # x ∈ (A ∖ C) ∪ (B ∖ A)
print("¿difieren en alguna región?", satisfiable(Xor(lhs, rhs)))
print("A ∖ (B ∖ C) frente a (A ∖ B) ∖ C:", satisfiable(Xor(And(a, Not(And(b, Not(c)))), And(a, Not(b), Not(c)))))

satisfiable returns False when no valuation distinguishes the sides (the identity holds), otherwise a specific counterexample region: here aa and cc true, bb false, region (1,0,1)(1, 0, 1) already found. For three or four sets this matches the truth table, but with dozens the table has too many rows and a SAT solver still works: the idea of satisfiability lessons. SymPy also computes interval images and preimages:

[ ]SymPy: interval images and preimagesBrowser
from sympy import Interval, Lambda, imageset, solveset, S

x = symbols("x", real=True)
f = Lambda(x, x**2)
A1, A2 = Interval(-2, -1), Interval(1, 2)
print("f(A1 ∩ A2) =", imageset(f, A1.intersect(A2)), "   f(A1) ∩ f(A2) =", imageset(f, A1).intersect(imageset(f, A2)))
print("f⁻¹([0, 4]) =", solveset(x**2 <= 4, x, S.Reals), "   f⁻¹({−1}) =", solveset(x**2 + 1, x, S.Reals))

The two lines show image/preimage asymmetry concretely: f(A1∩A2)=f(∅)=∅f(A_1 \cap A_2) = f(\varnothing) = \varnothing, whereas f(A1)∩f(A2)=[1,4]f(A_1) \cap f(A_2) = [1, 4].

Common mistakes

Exercises

QuizMembership or containment
Let A={∅,{∅},{1}}A = \{\varnothing, \{\varnothing\}, \{1\}\}. Which statements are true?

More than one answer may be correct.

NumericOne pair, one number
With Cantor pairing π(x,y)=(x+y)(x+y+1)2+y\pi(x, y) = \frac{(x+y)(x+y+1)}{2} + y, calculate π(3,4)\pi(3, 4).
NumericOne number, one pair
Let (x,y)=π−1(100)(x, y) = \pi^{-1}(100). Calculate yy.
QuizWhat commutes?
Let f:X→Yf: X \to Y be any function, A,A′⊆XA, A' \subseteq X and B,C⊆YB, C \subseteq Y. Which equalities or inclusions always hold?

More than one answer may be correct.

QuizWhat composition inherits
Let f:X→Yf: X \to Y and g:Y→Zg: Y \to Z with g∘fg \circ f bijective. What follows for certain?

More than one answer may be correct.

NumericCounting surjections
How many surjective functions are there from a 4-element set to a 3-element set?
NumericInjections from a power set
How many injective functions are there from P({1,2})\mathcal{P}(\{1, 2\}) to {1,2,3}\{1, 2, 3\}?
QuizCountable or not?
Which sets are countable?

More than one answer may be correct.

QuizWhy does it not fail for rationals?
Apply decimal diagonalization to an enumeration q0,q1,…q_0, q_1, \dots of all rationals in [0,1][0, 1], which exists because Q\Q is countable. Why is there no contradiction?
QuizSame size?
Which pairs of sets are equinumerous?

More than one answer may be correct.

CodeCantor inverse, exact
The starter code computes the inverse of Cantor pairing with math.sqrt. It passes small tests but fails on large numbers. Correct unpair(n) to use only integer arithmetic (math.isqrt, //) and return pair (x, y) with π(x,y)=n\pi(x, y) = n for any natural nn, however large.
import math

def pair(x, y):
  return (x + y) * (x + y + 1) // 2 + y

def unpair(n):
  w = int((math.sqrt(8 * n + 1) - 1) // 2)
  y = n - w * (w + 1) // 2
  return w - y, y
Shift+Enter to run

Summary

Key idea
Two sets have the same size if they can be paired one to one. Under this definition everything built from finite information (pairs, strings, programs, rationals) is countable, whereas infinite sequences, subsets of N\N, and reals are not: diagonalization builds a missing object for any list. Since programs are countable and problems uncountable, almost no problem has a program solving it.
  • Sets. Boolean set operations are logical connectives applied to “xx belongs.” An identity holds for all sets iff its formula is logical equivalence iff both sides contain the same Venn regions; any failure occurs with one element. Prove by double inclusion.
  • Functions. Injectivity means a left inverse and surjectivity a right inverse (the latter chooses preimages). If g∘fg \circ f is injective, so is ff; if surjective, so is gg; converses about the other function fail.
  • Image and preimage. Preimage preserves unions, intersections, and complements of arbitrary families and exists for every function. Image preserves only unions. Measurability and random variables are therefore defined using preimages.
  • Cardinality. ∣A∣≤∣B∣\abs{A} \le \abs{B} if an injection exists; injections each way give a bijection (Cantor–Schröder–Bernstein). An infinite set can be equinumerous with a proper part.
  • Countability. π(x,y)=Tx+y+y\pi(x, y) = T_{x+y} + y bijects N×N→N\N \times \N \to \N, and its inverse uses math.isqrt, not sqrt. Countable unions of countable sets, Q\Q, Σ∗\Sigma^*, and programs are countable.
  • Diagonal. d(k)=1−sk(k)d(k) = 1 - s_k(k) escapes any list: {0,1}N\{0, 1\}^{\N} and R\R are uncountable, and ∣A∣<∣P(A)∣\abs{A} < \abs{\mathcal{P}(A)} for every AA. Applied to programs, the same diagonal proves halting undecidable.