Python Sets
Unique values only, unordered, blazing fast membership tests.
Creating sets
Python
fruits = {"apple", "banana", "cherry"}
nums = {1, 2, 3, 4, 5}
empty = set() # NOT {} — that creates an empty dict!
# Remove duplicates from a list:
dupes = [1, 2, 2, 3, 3, 3]
unique = set(dupes) # {1, 2, 3}
Add and remove
Python
s = {1, 2, 3}
s.add(4) # {1,2,3,4}
s.add(2) # no-op — 2 already present
s.remove(3) # {1,2,4} — raises KeyError if not found
s.discard(99) # no error if not found
s.pop() # removes and returns an arbitrary item
s.clear() # empty set
Set operations
Python
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
a | b # {1,2,3,4,5,6} — union (all items)
a & b # {3,4} — intersection (common items)
a - b # {1,2} — difference (in a but not b)
b - a # {5,6} — difference (in b but not a)
a ^ b # {1,2,5,6} — symmetric difference (not in both)
# Method versions:
a.union(b)
a.intersection(b)
a.difference(b)
# Subset / superset checks:
{1,2} <= a # True — {1,2} is a subset of a
a >= {1,2} # True — a is a superset of {1,2}
Membership test is O(1)
Python
import time
big_list = list(range(10_000_000))
big_set = set(range(10_000_000))
# List: O(n) — scans every element
# 9_999_999 in big_list → ~100ms
# Set: O(1) — hash lookup, instant
# 9_999_999 in big_set → ~0.1ms
Key rule: sets need hashable items
Set elements must be hashable — you can't have a set of lists. Use frozenset if you need an immutable, hashable set:
frozenset([1, 2, 3]).