Python Set Union()

Union of a Set

 

The union() of two or more sets returns a set that contains all items from all the sets.

The result set contains distinct element that is if an item is present in more than one set, the result will contain only one appearance of this item.

∪ symbol denotes union of sets.

Python Set Union()

Let us understand this concept with an example, suppose there are two sets A and B, we have to find A ∪ B.

A = { 1 , 2, 3, 4, 5 }

B = { 1, 3, 5, 7, 9 }

A ∪ B = { 1, 2, 3, 4, 5, 7, 9 }

Syntax :


set1.union(set2,set3,…)
 

The parameter can be only one or more. You can compare as many sets as you like. Separate each set with a comma.

Return Type :

The union() method returns a new set with elements from the set and all other sets (passed as an argument).

If the argument is not passed to union(), it returns a shallow copy of the set.

Using the | operator


#union of sets using | operator

#example 1
set1 = {‘P’‘Y’‘T’‘H’‘O’‘N’ }
set2 = {‘C’‘O’‘D’‘I’‘N’‘G’ }
print( set1 | set2 )

#example 2
A = { 2468101112 }
B = { 3691215 }
C = { 481216 }
print( A | B | C )


Output :

{'Y', 'T', 'N', 'D', 'G', 'I', 'C', 'P', 'H', 'O'}

{2, 3, 4, 6, 8, 9, 10, 11, 12, 15, 16}

Using union() function


#union of sets using union() method

#example 1
set1 = {‘P’‘Y’‘T’‘H’‘O’‘N’ }
set2 = {‘C’‘O’‘D’‘I’‘N’‘G’ }
print( set1.union(set2) )

#example 2
A = { 2468101112 }
B = { 3691215 }
C = { 481216 }
print( A.union(B,C) )


Output :

{'Y', 'T', 'N', 'D', 'G', 'I', 'C', 'P', 'H', 'O'}

{2, 3, 4, 6, 8, 9, 10, 11, 12, 15, 16}