Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Python
Stage 5: Specialization

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 in is fast even for a million items, and why items must be hashable: str, int, float, bool and 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])) raises TypeError: 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. Use sorted() when you need a fixed order.

Done here? The practice set for Part 4 โ€” 8 exercises with solutions โ€” is on the part page.

Search the guide