Union() function in Python


In this article, we will be learning about union() i.e. one of the operations performed on the set() type. Union of all input sets is the smallest set which contains the elements from all sets excluding the duplicate elements present in sets.

Syntax

<set_1>.union(<set_2>,<set_3>.......)

Return type − <’set’> type

Symbol − It is denoted by the first letter of function i.e. ‘U’ in probability

Example

 Live Demo

# Python 3.x. set union() function
set_1 = {'a','b'}
set_2 = {'b','c','d'}
set_3 = {'b','c','d','e','f','g'}
   # union operation on two sets
print("set_1 U set_2 : ", set_1.union(set_2))
print("set_3 U set_2 : ", set_2.union(set_3))
print("set_1 U set_3 : ", set_1.union(set_3))
# union operation on three sets
print("set_1 U set_2 U set_3 :", set_1.union(set_2, set_3))

Output

set_1 U set_2 : {'a', 'd', 'c', 'b'}
set_3 U set_2 : {'e', 'c', 'd', 'b', 'f', 'g'}
set_1 U set_3 : {'e', 'c', 'd', 'b', 'a', 'f', 'g'}
set_1 U set_2 U set_3 : {'e', 'c', 'd', 'b', 'a', 'f', 'g'}

The output indicates that duplicate elements are not counted while forming the output.

Alternate syntax for implementing set operations.

Example

 Live Demo

# Python 3.x. set union() function
set_1 = {'a','b'}
set_2 = {'b','c','d'}
set_3 = {'b','c','d','e','f','g'}
   # union operation on two sets
print("set_1 U set_2 : ", set_1|set_2)
print("set_3 U set_2 : ", set_2|set_3)
print("set_1 U set_3 : ", set_1|set_3)
# union operation on three sets
print("set_1 U set_2 U set_3 :", set_1|set_2|set_3)

The output produced by the above code is identical to one discussed the previous illustration. Here instead of implementing .union() we use this symbol “|” which has the identical functionality.

Union operator can also be used for lists by converting them to set() type using explicit type casting

Syntax

list(set(lst_1) | set(lst_2))

Conclusion

In this article, we learnt about union() function and its working on set & list type of data structures.

Updated on: 29-Aug-2019

263 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements