Join Sets
Joining Sets in Python
1. Union (union()
or |
Operator):
# Union using union() method
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1.union(set2)
# or
union_set = set1 | set2
# Result: {1, 2, 3, 4, 5}
2. Update (update()
Method or |=
Operator):
# Update using update() method
set1 = {1, 2, 3}
set2 = {3, 4, 5}
set1.update(set2)
# or
set1 |= set2
# Now, set1 is {1, 2, 3, 4, 5}
3. Intersection (intersection()
or &
Operator):
# Intersection using intersection() method
set1 = {1, 2, 3}
set2 = {3, 4, 5}
intersection_set = set1.intersection(set2)
# or
intersection_set = set1 & set2
# Result: {3}
4. Intersection Update (intersection_update()
Method or &=
Operator):
# Intersection update using intersection_update() method
set1 = {1, 2, 3}
set2 = {3, 4, 5}
set1.intersection_update(set2)
# or
set1 &= set2
# Now, set1 is {3}
5. Symmetric Difference (symmetric_difference()
or ^
Operator):
# Symmetric difference using symmetric_difference() method
set1 = {1, 2, 3}
set2 = {3, 4, 5}
symmetric_diff_set = set1.symmetric_difference(set2)
# or
symmetric_diff_set = set1 ^ set2
# Result: {1, 2, 4, 5}
6. Symmetric Difference Update (symmetric_difference_update()
Method or ^=
Operator):
# Symmetric difference update using symmetric_difference_update() method
set1 = {1, 2, 3}
set2 = {3, 4, 5}
set1.symmetric_difference_update(set2)
# or
set1 ^= set2
# Now, set1 is {1, 2, 4, 5}
These methods provide various ways to combine sets or update a set with elements from another set. Choose the method that best suits your specific use case.