Set Theory · Introduction
Lesson 2
A set is a collection of elements: for each element, it can be determined whether it belongs to the set or not, with no repetitions allowed (no element can belong to the set more than once). Note that we say nothing about the nature of the elements—they can be numbers, strings, pencils, or even sets themselves. The empty set (containing no elements) is denoted by \(\{\}\) or \(\varnothing\). The size of a set \(A\) is the number of elements it contains and is denoted by \(|A|\): \[|\{2, 5, 3\}|=3,\quad |\varnothing|=0 \ .\]
We say that \(x\) belongs to \(A\) or \(A\) contains \(x\) and write \(x \in A\), if \(x\) is an element of \(A\). We say that \(A\) is a subset of \(B\) and write \(A \subseteq B\), if every element of \(A\) is also an element of \(B\).
Standard operations on sets are similar to Boolean operations.
- Union (disjunction): \[A \cup B =\{x \colon x \in A \lor x \in B\}\]
- Intersection (conjunction): \[A \cap B =\{x \colon x \in A \land x \in B\}\]
- Difference: \[A \setminus B =\{x \colon x \in A \land x \not \in B\}\]
- Symmetric difference (exclusive OR): \[A \triangle B =\{x \colon x \in A \oplus x \in B\}\]
When there are few sets, it is convenient to represent them using so-called Venn diagrams (also known as Euler–Venn diagrams). The code below adjusts the sizes and positions of the circles so that the sizes of the various overlapping parts are in the correct proportions.
import matplotlib.pyplot as plt
from matplotlib_venn import venn3
venn3(subsets=(10, 8, 22, 6, 9, 4, 2))
plt.savefig('venn3.png') 
A set can be defined in various ways:
- by listing its elements: \(A=\{2, 13, 6, 15, 4\}\);
- by describing its elements: \(B\) is the set of all positive two-digit integers;
- by set-builder notation: \(C=\{x \in A \colon \text{\(x\) is prime}\}\);
- using set-theoretic operations: \(D=A \cap B\), \(E=A \setminus B\).
Let us emphasize that a set does not have to contain elements of the same “type.” In the example below, we add a number, a string, and another set to a set.
from sympy.ntheory import isprime
a = {2, 13, 6, 15, 4}
b = set(range(10, 100))
c = {x for x in a if isprime(x)}
print(c)
d = a.intersection(b)
print(d)
e = a.difference(b)
print(e)
f = frozenset({'hello', 2})
g = {7, f, 'world'}
print(g, len(g)){2, 13}
{13, 15}
{2, 4, 6}
{frozenset({'hello', 2}), 'world', 7} 3