Python Tutorial: Sets
Unique collections with lightning-fast lookups. Remove duplicates, find intersections, and compare groups.
What you'll learn in this Python sets tutorial
This interactive Python tutorial has 8 hands-on exercises. Estimated time: 14 minutes.
- What's a set? — A set is like a bag of unique items — no duplicates allowed. Throw in 5 red balls and 3 blue balls, the bag only remembe…
- Remove duplicates from a list — The most common use of sets: deduplication. Convert a list to a set, duplicates gone.
- Add and remove — `.add(item)` adds one item. `.discard(item)` removes it (silently does nothing if missing). `.remove(item)` raises an er…
- Union — combine two groups — Set operations are like Venn diagrams.
- Intersection — what's in common — `A & B` (intersection) = only items in BOTH sets.
- Difference — what's unique to one — `A - B` = items in A that are NOT in B.
- Fast lookups — why sets matter — Checking `item in set` is nearly instant — O(1), no matter how large the set. Checking `item in list` gets slower as the…
- Build a tag analyzer 🏷️ — Two blog posts have tags. Find: