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.
The syntax of this method is as follows.
set.union(set1, set2..., setn)
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.
The return value is a set that contains joined elements of the sets on which union()
is applied.
Two sets are merged through the union()
method in the code below.
#set declarationset1 = {"1", "2", "3"}set2 = {"c", "b", "a"}#union application on setssetUnion = set1.union(set2)print(setUnion)
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 declarationset1 = {"1", "2", "3"}set2 = {"6", "7", "8"}set3 = {"3", "4", "5"}#union application on setssetUnion = set1.union(set2, set3)print(setUnion)