Part 04 / Topic 3 of 11
Set
A set keeps only unique items and has no order (no indexing). Think of the guest list at a door: each name appears once. Use curly brackets {} or set().
Checking x in my_set is very fast.
Real-world example: unique visitors and common friends.
visits = ["ravi", "asha", "ravi", "meena", "asha"]
unique_visitors = set(visits)
print(len(unique_visitors)) # 3
tags = {"python", "coding"}
tags.add("beginner")
tags.add("python") # already there, nothing happens
tags.remove("coding") # error if missing
tags.discard("java") # no error if missing
print(sorted(tags)) # ['beginner', 'python']
ravi = {"Asha", "Karan", "Meena"}
priya = {"Meena", "Karan", "Vikram"}
print(sorted(ravi | priya)) # ['Asha', 'Karan', 'Meena', 'Vikram']
print(sorted(ravi & priya)) # ['Karan', 'Meena']
print(sorted(ravi - priya)) # ['Asha']
empty = set() # {} makes an empty DICT, not a set
print(type(empty)) # <class 'set'>
| Operation | Symbol | Method | Meaning |
|---|---|---|---|
| Union | a | b |
a.union(b) |
in a or b |
| Intersection | a & b |
a.intersection(b) |
in both |
| Difference | a - b |
a.difference(b) |
in a but not b |
| Symmetric diff | a ^ b |
a.symmetric_difference(b) |
in one, not both |
๐ Going deeper: sets (and dict keys) use hashing: Python turns each item into a number that points straight to where it is stored. That is why
inis fast even for a million items, and why items must be hashable:str,int,float,booland tuples work; lists, dicts and sets do not (TypeError: cannot use 'list' as a set element (unhashable type: 'list')). A tuple is hashable only if everything inside it is:hash((1, "a"))works,hash((1, [2]))raisesTypeError: unhashable type: 'list'. The order of a set follows these hash numbers, not the order you added items. For strings, Python mixes a random value into the hash each time the program starts (a security feature), so{"apple", "mango"}can print in a different order on every run. Usesorted()when you need a fixed order.
Done here? The practice set for Part 4 โ 8 exercises with solutions โ is on the part page.