What is the union() method in Python?

The union() method in Python merges the items of two or more sets. If two or more sets contain the same element, it will appear only once in the returning set.

Syntax

The syntax of this method is as follows.


set.union(set1, set2..., setn)

Parameters

The union() method takes one required parameter, which is a set. Apart from this parameter, it can take multiple optional arguments, which are also set.

Return value

The return value is a set that contains joined elements of the sets on which union() is applied.

Code

Example 1

Two sets are merged through the union() method in the code below.

#set declaration
set1 = {"1", "2", "3"}
set2 = {"c", "b", "a"}
#union application on sets
setUnion = set1.union(set2)
print(setUnion)

Example 2

The union() method is applied at more than one set and returns a set that contains all the elements of these sets.

Also, set1 and set3 contain some values that are the same, and hence they appear only once in the resulting set.

#set declaration
set1 = {"1", "2", "3"}
set2 = {"6", "7", "8"}
set3 = {"3", "4", "5"}
#union application on sets
setUnion = set1.union(set2, set3)
print(setUnion)

Free Resources