set — A Collection Without Duplicates
set — A Collection Without Duplicates
🎯 After Reading This Lesson
Once you finish this lesson, you will be able to confidently do the following 3 things.
- ▸✅ Use
setfor duplicate removal + set operations (& | -) - ▸✅ Know when to convert between
listandset - ▸✅ Understand the hashable requirement (for set/dict keys)
Keep these goals as a checklist, and close the lesson once you can answer all of them.
8 set Patterns — Code + Output
set = no order · no duplicates · hash-based. Membership check O(1) — 100x faster than a list. Mirrors mathematical set operations directly.
1. Creating a Set
2. Adding and Removing
add / remove / discard / pop — similar to list, but no order.
3. in — O(1) Membership Check (the real power of set)
If you need to frequently check whether a value exists, always use a set.
4. Set Operations — Just Like Math
5. Subset and Superset
6. Set Comprehension
7. Practical Pattern — Removing Duplicates
8. frozenset — Immutable Set
A regular set cannot be used as a dict key, but a frozenset can because it is immutable.
list vs set vs dict — When to Use Which
One-Line Summary
🐍 Try It Out — set — Run It Yourself
🤖 Try Asking AI Like This
Knowing the concepts in this lesson lets you give AI specific instructions. Instead of a vague 'fix this,' you make vocabulary-driven requests — that's where token savings start.
- ▸'Replace the duplicate removal in this list with a set'
- ▸'Rewrite this dict merge using dict | dict (Python 3.9+)'
Why This Reduces Tokens
Without the vocabulary, even after receiving an AI answer you have to ask 'What does that mean?' again. That follow-up question is what burns tokens. Learn the concept once and the conversation ends in one round.