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}.

Union of two sets

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.

Syntax:
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.

ExampleEdit & Run
set1 = {0, 2, 4, 6, 8}
set2 = {1, 3, 5, 7, 9}

result = set1.union(set2)
print(result)
Output:
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}[Finished in 0.01103966380469501s]

In the following example, we pass multiple sets to the union() method. 

ExampleEdit & Run
set1 = {0, 2, 4, 6, 8}
set2 = {1, 3}
set3 = {5, 7, 9}

result = set1.union(set2, set3)
print(result)
Output:
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}[Finished in 0.009781931061297655s]

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.

Syntax:
set_a | set_b

With this approach, both arguments must be sets. 

ExampleEdit & Run
set1 = {0, 2, 4, 6, 8}
set2 = {1, 3, 5, 7, 9}

result = set1 | set2 #the union
print(result)
Output:
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}[Finished in 0.010499328142032027s]
ExampleEdit & Run

with characters

set1 = {"A", "B"}
set2 = {"C", "D"}

result = set1 | set2 #the union
print(result)
Output:
{'C', 'D', 'B', 'A'}[Finished in 0.01104891486465931s]