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
- No
+Operator: Sets cannot be concatenated using+. Always use the pipe operator|or.union(). - Modifying vs Returning:
set1.union(set2)returns a new set, whereasset1.update(set2)modifiesset1in place.
Quick Summary
- Union (
|or.union()): Merges all elements from both sets without duplicates. - Intersection (
&or.intersection()): Finds elements that exist in both sets simultaneously. - Difference (
-or.difference()): Extracts elements that exist in the first set but NOT in the second. - Symmetric Difference (
^): Returns items present in either set, but not in their intersection. - Relationship Checks:
.issubset()and.issuperset()verify complete containment.
What's Next?
Let's transition to Module 11: Dictionaries to learn how to store labeled information using key-value pairs!