Ojasa Mirai

Ojasa Mirai

Python

Loading...

Learning Level

🟢 Beginner🔵 Advanced
🎯 Why Data Structures Matter📋 Lists: Ordered Collections🔑 Dictionaries: Key-Value Pairs🎪 Sets: Unique Values & Speed📦 Tuples: Immutable Sequences⚖️ Comparing All Data Structures🔧 Mastering List Methods⚡ Advanced Dictionary Patterns🔄 Power of Set Operations🏗️ Building Nested Structures⚙️ Performance Tuning & Optimization
Python/Data Structures/Set Operations

🔄 Set Operations — Combining and Comparing Sets

Sets support powerful operations to combine, compare, and filter collections.


🎯 Union: Combine All Items

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: Find Common Items

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'}

🎨 Real-World Example: Finding Shared Interests

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}")

📊 Set Operations Quick Reference

OperationOperatorMethodPurpose
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

🔑 Key Takeaways

  • ✅ Union (`|`) combines all unique items from both sets
  • ✅ Intersection (`&`) finds common items
  • ✅ Difference (`-`) finds unique items in the first set
  • ✅ Use for filtering and comparing data
  • ✅ Faster than loops for large collections

Ready to practice? Challenges | Quiz


Resources

Python Docs

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

Courses

PythonFastapiReactJSCloud

© 2026 Ojasa Mirai. All rights reserved.

TwitterGitHubLinkedIn