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.
In the following example, we pass multiple sets to the union()
method.
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.