Note Set operations are extremely fast (O(min(len(a), len(b))) for intersection). Use them instead of nested loops for membership checks.
set unionset intersectionset differencecompare setsvenn diagram
frozenset (Immutable Set)
syntax
fs = frozenset(iterable)
example
permissions = frozenset(["read", "write"])
print("read"in permissions)
# Can be used as a dictionary key
cache = {permissions: "admin"}
print(cache[frozenset(["read", "write"])])
output
True
admin
Note frozenset is hashable, so it can be used as a dict key or as an element inside another set. Regular sets cannot.
frozensetimmutable sethashable setset as key
Set Comprehensions
syntax
{expression for item in iterable if condition}
example
emails = ["a@test.com", "B@TEST.COM", "a@test.com", "c@test.com"]
unique_lower = {e.lower() for e in emails}
print(unique_lower)
output
{'a@test.com', 'b@test.com', 'c@test.com'}
Note Set comprehensions automatically deduplicate results. Useful for extracting unique transformed values from a collection.
set comprehensionunique valuesdeduplicatebuild set
Set Mutation Methods
syntax
s.add(elem)
s.discard(elem)
s.remove(elem)
example
active = {"alice", "bob"}
active.add("carol")
active.discard("bob")
active.discard("nonexistent")
print(active)
output
{'alice', 'carol'}
Note discard() silently ignores missing elements. remove() raises KeyError if the element is not found. Prefer discard() when absence is acceptable.