SyntaxStudy
Sign Up
Python Beginner 8 min read

Set Operations

Set Operations

Sets support mathematical set operations: union, intersection, difference, and symmetric difference — both as methods and as operators.

Union (| or union())

a = {1, 2, 3, 4}
b = {3, 4, 5, 6}

print(a | b)           # {1, 2, 3, 4, 5, 6}
print(a.union(b))      # same result

Intersection (& or intersection())

print(a & b)           # {3, 4}
print(a.intersection(b))

Difference (- or difference())

print(a - b)           # {1, 2} (in a, not in b)
print(b - a)           # {5, 6} (in b, not in a)

Symmetric Difference (^ or symmetric_difference())

print(a ^ b)           # {1, 2, 5, 6}
print(a.symmetric_difference(b))

Subset & Superset

c = {1, 2}
print(c.issubset(a))   # True  (c ⊆ a)
print(a.issuperset(c)) # True  (a ⊇ c)
print(a.isdisjoint({7, 8}))  # True (no common elements)

Update In-Place

a |= {10, 11}   # union update
a &= b          # intersection update
a -= b          # difference update
Example
python_devs = {"Alice", "Bob", "Carol"}
js_devs = {"Bob", "Dave", "Carol"}

both = python_devs & js_devs
print("Both:", both)       # Bob, Carol
only_py = python_devs - js_devs
print("Python only:", only_py)
all_devs = python_devs | js_devs
print("Total:", len(all_devs))
Pro Tip

The ^ (symmetric difference) operator gives you elements that are in exactly one of the two sets — useful for finding what changed.