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. Example: `set1 | set2`Intersection (
&
): Finds common elements between sets. Example: `set1 & set2`Difference (
-
): Removes elements present in another set. Example: `set1 - set2`Symmetric Difference (
^
): Elements in either set but not both. 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. 🚀