Python Set Operations
Set operations combine two sets in different ways. Two sets can overlap on the items they share.
Union joins both sets
Union collects every item from both sets.
a = {1, 2, 3}
b = {3, 4}
print(sorted(a | b))
print(sorted(a.union(b)))Intersection keeps the overlap
Intersection keeps only the shared items.
a = {1, 2, 3}
b = {3, 4}
print(sorted(a & b))
print(sorted(a.intersection(b)))Difference keeps the rest
Difference drops the items found in the other set.
a = {1, 2, 3}
b = {3, 4}
print(sorted(a - b))
print(sorted(b - a))Symmetric difference skips the overlap
It keeps items in one set only.
a = {1, 2, 3}
b = {3, 4}
print(sorted(a ^ b))
print(sorted(a.symmetric_difference(b)))Results are new sets
The first set does not change here.
a = {1, 2}
b = {2, 3}
both = a | b
print(sorted(a))
print(sorted(both))Example
art = {"Ana", "Ben", "Cy", "Dee"}
music = {"Ben", "Cy", "Eli", "Fay"}
both = art & music
only_one = art ^ music
either = art | music
print("Both:", sorted(both))
print("Only one:", sorted(only_one))
print("Either:", sorted(either))Key points
- Union: all items that are in either set
- Intersection: only items that are in both sets
- Difference: items in the first set but not the second set
- Symmetric difference: items in one set but not in both sets
- Use | for union, & for intersection, - for difference, and ^ for symmetric difference
In this example, art holds the art class roster. The music set holds the music class roster. The & operator finds Ben and Cy in both sets. The ^ operator finds the names in one set only. The | operator joins every name from both sets. Each print uses sorted() for a stable order.
Note
Each operation builds a new set — the first sets stay unchanged
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
What does {1, 2, 3} & {3, 4} give?