Topic 53 of 64
Union,
Overview
Sets support mathematical set operations natively: union, intersection, difference, and symmetric difference. These are O(min(len(s1), len(s2))) and ideal for comparing groups, finding common elements, and computing differences.
Syntax
python
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
# Union (all elements)
a | b # {1, 2, 3, 4, 5, 6}
a.union(b)
# Intersection (common)
a & b # {3, 4}
a.intersection(b)
# Difference (in a but not b)
a - b # {1, 2}
a.difference(b)
# Symmetric difference (in either but not both)
a ^ b # {1, 2, 5, 6}
# Subset / superset checks
{1, 2} <= {1, 2, 3} # True (subset)Common Pitfalls
- Set operations return new sets — they don't modify the originals. Use |=, &=, -=, ^= for in-place updates.
- issubset() and issuperset() work with any iterable, not just sets — a <= b requires both to be sets.
- Interview tip: Symmetric difference (^) is often missed — it's the XOR of two sets, containing elements in one but not both.
Real-World Example
Compare user permissions between two roles
example
python
admin_perms = {"read", "write", "delete", "admin"}
editor_perms = {"read", "write", "publish"}
# What admins have that editors don't
admin_only = admin_perms - editor_perms
print(f"Admin exclusive: {admin_only}") # {'delete', 'admin'}
# Shared permissions
shared = admin_perms & editor_perms
print(f"Shared: {shared}") # {'read', 'write'}
# All permissions across both roles
all_perms = admin_perms | editor_perms
print(f"All: {all_perms}")