Set Mathematical Operations
Sets let you perform Venn diagram math operations easily: combining collections, finding shared items, or finding items that exist in only one group.
Union (| or .union())
A Union combines all unique items from both sets together into one big set:
frontend = {"HTML", "CSS", "JavaScript"}
backend = {"Python", "SQL", "JavaScript"}
# Combine both teams
fullstack = frontend | backend
print(fullstack) # Output: {'HTML', 'CSS', 'JavaScript', 'Python', 'SQL'}
Intersection (& or .intersection())
An Intersection finds only the items that exist inside both sets at the same time:
frontend = {"HTML", "CSS", "JavaScript"}
backend = {"Python", "SQL", "JavaScript"}
# Find overlapping skills
shared_skills = frontend & backend
print(shared_skills) # Output: {'JavaScript'}
Difference (- or .difference())
A Difference finds items that are inside the first set, but NOT in the second set:
frontend = {"HTML", "CSS", "JavaScript"}
backend = {"Python", "SQL", "JavaScript"}
# Skills unique to frontend only
only_frontend = frontend - backend
print(only_frontend) # Output: {'HTML', 'CSS'}
Symmetric Difference (^ or .symmetric_difference())
A Symmetric Difference finds items that exist in one set or the other, but not in both:
frontend = {"HTML", "CSS", "JavaScript"}
backend = {"Python", "SQL", "JavaScript"}
non_overlapping = frontend ^ backend
print(non_overlapping) # Output: {'HTML', 'CSS', 'Python', 'SQL'}
Common Beginner Mistakes
Using + operator to combine sets
# Wrong - sets do not support addition using +
set1 = {1, 2}
set2 = {3, 4}
combined = set1 + set2 # TypeError!
# Right - use the union pipe | operator or .union() method
combined = set1 | set2
What's Next?
Let's transition to Module 11: Dictionaries to learn how to store labeled information using key-value pairs.