Lesson 23 of 55
8 mins readPython Sets & Set Algebraic Operations
In Plain English
Sets represent unordered collections of unique elements with mathematical set algebra: union (∪), intersect (∩), setdiff, and subset testing (issubset or ⊆).
Deep Dive: How It Works
Set Construction: Set([1, 2, 2, 3]) results in Set([1, 2, 3]).
Set Operations: union(A, B) (or A ∪ B), intersect(A, B) (or A ∩ B), setdiff(A, B).
Membership: in(3, S) (or 3 ∈ S) tests element membership in O(1) time.
Core Rules to Remember

Uniqueness Guarantees: Duplicates are eliminated automatically upon insertion.

Mathematical Unicode Set Symbols: Use ∪, ∩, ⊆, ∈ directly in code.
Live Interactive Example
Hit Run Code to see it liveSet Algebra Operations
Python 3.12
1
2
3
4
5
6
7
8
9
10
11
Output Console
Click "Run Code" to view the rendered output.
How it works: intersect finds shared items (TypeScript); setdiff removes items present in the second set.
Your Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Micro Exercise
Find Shared Elements with Intersect
Define `setA = Set([1, 2, 3, 4])` and `setB = Set([3, 4, 5, 6])`.
Compute `shared = intersect(setA, setB)`.
Print `"Shared count: $(length(shared))"`.
1
2
3
4
Sandbox Output
Click "Run & Check" to test your solution.
Finished reading and practicing?
Mark this lesson as completed to update your course progress.