Sets in Python are unordered collections of unique elements. Here’s a concise guide to common set operations:

🔢 Basic Operations

  • Union (|): Combines elements from two sets.

    Union of Sets
    Example: `set1 | set2`
  • Intersection (&): Finds common elements between sets.

    Intersection of Sets
    Example: `set1 & set2`
  • Difference (-): Removes elements present in another set.

    Difference of Sets
    Example: `set1 - set2`
  • Symmetric Difference (^): Elements in either set but not both.

    Symmetric Difference of Sets
    Example: `set1 ^ set2`

📚 Practical Tips

  • Use in to check membership: if x in my_set:
  • Iterate with for loops:
    for item in my_set:  
        print(item)  
    
  • Clear a set with .clear() or reassign it.

For deeper insights into Python data structures, check out our Python Data Structures Guide. 🚀

Python Set Operation