
Python
Learning Level
Sets support powerful operations to combine, compare, and filter collections.
Union (`|` or `union()`) combines all items from both sets, removing duplicates automatically.
fruits = {"apple", "banana", "orange"}
vegetables = {"carrot", "broccoli", "apple"}
# Both ways work
combined = fruits | vegetables
combined = fruits.union(vegetables)
print(combined) # {'apple', 'banana', 'orange', 'carrot', 'broccoli'}Intersection (`&` or `intersection()`) finds items that appear in both sets.
python_students = {"Alice", "Bob", "Carol", "David"}
math_students = {"Alice", "Carol", "Eve", "Frank"}
# Students taking both classes
both_classes = python_students & math_students
print(both_classes) # {'Alice', 'Carol'}alice_hobbies = {"reading", "coding", "hiking", "gaming"}
bob_hobbies = {"gaming", "movies", "hiking", "cooking"}
# Find common hobbies
shared = alice_hobbies & bob_hobbies
print(f"Shared interests: {shared}") # {'hiking', 'gaming'}
# All hobbies between them
all_hobbies = alice_hobbies | bob_hobbies
print(f"All interests: {all_hobbies}")| Operation | Operator | Method | Purpose | |
|---|---|---|---|---|
| Union | `\ | ` | `.union()` | All items from both |
| Intersection | `&` | `.intersection()` | Common items only | |
| Difference | `-` | `.difference()` | Items in first, not second | |
| Symmetric Diff | `^` | `.symmetric_difference()` | Items in either, not both |
Ready to practice? Challenges | Quiz
Resources
Ojasa Mirai
Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.
Learn Deep • Build Real • Verify Skills • Launch Forward