Union () function in Python

Python Methods and Functions

The symbol for denoting set union is & # 39; U & # 39;
Examples :

 Input: Let set A = {2, 4, 5, 6} and set B = {4, 6, 7, 8} Output: {2, 4, 5, 6, 7, 8} Explanation: Taking every element of both the sets A and B, without repeating any element, we get a new set = {2, 4, 5, 6, 7, 8}. This new set contains all the elements of set A and all the elements of set B with no repetition of elements and is named as union of set A and B. 

Syntax :

set1.union (set2, set3, set4….)
In parameters, any number of sets can be given

Returned value:

The union () function returns a set, which has the union of all sets (set1, set2, set3 ...) with set1.
It returns a copy of set1 only if no parameter is passed.

 The above approach is implemented in Python3:

# Python3 program for the union () function

 

set1 = { 2 , 4 , 5 , 6

set2 = { 4 , 6 , 7 , 8

set3 =   { 7 , 8 , 9 , 10 }

 
# combining two sets

print ( "set1 U set2: " , set1.union (set2))

  
# combining three sets

print ( "set1 U set2 U set3:" , set1.union (set2, set3))

Exit :

 set1 U set2: {2, 4, 5, 6, 7, 8} set1 U set2 U set3: {2, 4, 5, 6, 7, 8, 9, 10} 

Practical Applications :

Most probabilistic problems require the concept of union of sets.