A union of two sets is a set that contains all the elements of both sets, without any duplicates. It is denoted by the symbol "∪
". For example, the union of the sets {1, 2, 3}
and {3, 4, 5}
is {1, 2, 3, 4, 5}
.
The set.union()
method is used to get the union of two or more sets. It combines the elements of the sets into a single set by removing the duplicate elements, if any.
union_set = set1.union(set2, ...)
set2 |
This can be a set or any other iterable object. Multiple iterables can be passed. |
The method returns a new set with all the unique elements from set1 and set2 and any other set passed as argument.
set1 = {0, 2, 4, 6, 8}
set2 = {1, 3, 5, 7, 9}
result = set1.union(set2)
print(result)
In the following example, we pass multiple sets to the union()
method.
set1 = {0, 2, 4, 6, 8}
set2 = {1, 3}
set3 = {5, 7, 9}
result = set1.union(set2, set3)
print(result)
Using the |
operator instead
The pipe (|
) is the operator version of the union()
method. Similarly it returns a new set containing the distinct elements from both sets.
set_a | set_b
With this approach, both arguments must be sets.
set1 = {0, 2, 4, 6, 8}
set2 = {1, 3, 5, 7, 9}
result = set1 | set2 #the union
print(result)
with characters
set1 = {"A", "B"}
set2 = {"C", "D"}
result = set1 | set2 #the union
print(result)