Join Sets
Joining Sets
Sets support several operations to combine or compare their elements. These operations return new sets or modify existing ones:
- **union()**: Returns a new set containing all items from both sets
- **update()**: Adds all items from another set into the current set
- **intersection()**: Returns a set with elements common to both sets
- **intersection_update()**: Keeps only items present in both sets (in-place)
- **difference()**: Returns items only in the first set
- **difference_update()**: Removes items found in another set (in-place)
- **symmetric_difference()**: Returns elements in either set, but not in both
- **symmetric_difference_update()**: Updates a set with the symmetric difference
Example
# Joining sets examples
set1 = {"a", "b", "c"}
set2 = {"c", "d", "e"}
# Union
union_set = set1.union(set2)
print("Union:", union_set)
# Intersection
intersection_set = set1.intersection(set2)
print("Intersection:", intersection_set)
# Difference
difference_set = set1.difference(set2)
print("Difference:", difference_set)
# Symmetric difference
symmetric_set = set1.symmetric_difference(set2)
print("Symmetric Difference:", symmetric_set)
Output
Union: {'a', 'b', 'c', 'd', 'e'} Intersection: {'c'} Difference: {'a', 'b'} Symmetric Difference: {'a', 'b', 'd', 'e'}