What is a set?#
A set is a collection of unique items with no order. Sets use curly braces:
colors = {"red", "green", "blue"}
numbers = {1, 2, 3, 2, 1} # duplicates removed -> {1, 2, 3}
empty = set() # NOT {} - that's an empty dict
Key properties:
- No duplicates - each value appears once.
- Unordered - no index, no slicing; printing order may vary.
- Mutable - you can add/remove items, but the items themselves must be immutable (numbers, strings, tuples - not lists).
Removing duplicates - the #1 use#
Converting to a set loses the original order. If order matters, use list(dict.fromkeys(items)) - it removes duplicates and keeps the first-seen order.
Fast membership testing#
Checking x in my_set is extremely fast, even with millions of items (lists check one by one):
blocked_users = {"spam1", "bot42", "fake99"}
if username in blocked_users:
print("Access denied")
Adding and removing#
| Method | Purpose |
|---|---|
add(x) |
add one item |
update(iterable) |
add many items |
remove(x) |
remove x - KeyError if missing |
discard(x) |
remove x - no error if missing |
pop() |
remove and return an arbitrary item |
clear() |
empty the set |
Set operations (like maths Venn diagrams)#
| Operation | Operator | Method | Meaning |
|---|---|---|---|
| Union | a | b |
a.union(b) |
all items from both |
| Intersection | a & b |
a.intersection(b) |
items in both |
| Difference | a - b |
a.difference(b) |
in a but not in b |
| Symmetric difference | a ^ b |
a.symmetric_difference(b) |
in exactly one of them |
Set operations को Venn diagram की तरह सोचें - दो गोले जो थोड़े overlap करते हैं:
- Union (
|) - दोनों गोलों की सारी चीज़ें (कोई भी course करने वाले students) - Intersection (
&) - बीच का common हिस्सा (दोनों courses करने वाले) - Difference (
-) - सिर्फ पहले गोले का हिस्सा, common हटाकर (सिर्फ Python वाले) - Symmetric difference (
^) - दोनों गोलों के अलग-अलग हिस्से, common हटाकर (जो सिर्फ एक course में हैं)
Subset and superset#
frozenset - an immutable set#
frozenset can't be changed after creation, so it can be used as a dictionary key or inside another set:
weekend = frozenset({"Sat", "Sun"})
When to use a set#
| Use a set when you need... | Example |
|---|---|
| unique values | unique customers, unique words |
| fast "is it there?" checks | blocked IPs, valid coupon codes |
| comparisons between groups | common friends, missing items |
Summary#
- Sets hold unique, unordered items:
{1, 2, 3}; empty set isset(). set(list)removes duplicates;inchecks are very fast.add,update,remove,discard,pop,clear.- Union
|, intersection&, difference-, symmetric difference^. - No indexing - convert to a list (
sorted(s)) if you need order.