In Python Sets, you can join (or combine)
sets using the union(), update(), |
operator, and other set operations like intersection() and difference()
.
These methods allow you to perform various operations to merge sets or find common/different elements between sets.
Using union()
The union()
method returns a new set with all elements from the original sets. It does not modify the original sets.
set1 = {1, 2, 3} set2 = {3, 4, 5} union_set = set1.union(set2) print(union_set) # {1, 2, 3, 4, 5}
Using update()
The update()
method adds elements from another set (or any iterable) to the original set.
set1 = {1, 2, 3} set2 = {3, 4, 5} set1.update(set2) print(set1) # {1, 2, 3, 4, 5}
Using the | Operator
The |
operator can be used to perform a union of sets.
set1 = {1, 2, 3} set2 = {3, 4, 5} union_set = set1 | set2 print(union_set) # {1, 2, 3, 4, 5}
Other Set Operations
Intersection
The intersection()
method returns a set with elements that are common to both sets.
set1 = {1, 2, 3} set2 = {3, 4, 5} intersection_set = set1.intersection(set2) print(intersection_set) # {3}
Difference
The difference()
method returns a set with elements that are in the first set but not in the second set.
set1 = {1, 2, 3} set2 = {3, 4, 5} difference_set = set1.difference(set2) print(difference_set) # {1, 2}
Symmetric Difference
The symmetric_difference()
method returns a set with elements that are in either of the sets, but not in both.
set1 = {1, 2, 3} set2 = {3, 4, 5} symmetric_difference_set = set1.symmetric_difference(set2) print(symmetric_difference_set) # {1, 2, 4, 5}
These methods provide powerful tools for combining and comparing sets, allowing you to perform various set operations efficiently.