In this tutorial, we are going to learn all about Python set union method. Set union function in python is used to return all the items from both sets or ( all sets ), duplicate items are excluded.
You should have basic knowledge of Python set, To understand this set method.
Headings of Contents
Python Set union() Method
Python set union method is used to return a set that contains all the items from original sets as well as specified sets.
If an item present more than one time, Then result will contain only one item. set union function in python accepts more than one set as a parameter.
Syntax
The syntax of union function in python is:-
set.union(set1, set2, set3,.....set)
Parameter value
The set union in python accepts more than one set as a parameter separated by commas.
Python set union example
Example
In this example, we will python set union method to return a set that contains items from both sets.
set1 = { 'Python', 'Java', 'JavaScript', 'C++'}
set2 = {'Python', 'HTML', 'JavaScript', 'Bootstrap'}
result = set1.union(set2)
print(result)
Output
{'Java', 'Javascript', 'C++', 'HTML', 'Bootstrap', 'Python'}
Example
Apply set union method on more than two sets.
set1 = { 'Python', 'Java', 'JavaScript', 'C++'}
set2 = {'Python', 'HTML', 'JavaScript', 'Bootstrap'}
set3 = {'R', 'Ruby', 'JavaScript', 'Django'}
result = set1.union(set2, set3)
print(result)
Output
{'Javascript', 'Django', 'Python', 'Java', 'Ruby', 'HTML', 'Bootstrap', 'R', 'C++'}
Conclusion
In this article, you have learned all about the python set union method. set union python returns new sets that contain items from both sets and treat duplicate items to once.
set union method is completely difference from set intersection method because union contains all items from both sets but intersection contains items that are exist in both sets.
If you like this article, keep visiting and learn your Python’s more topics.
Other set methods
- Set add() method
- Set clear() method
- Set difference() method
- Set difference_update() method
- Set discard() method
- Set intersection() method
- Set intersection_update() method
For More information:- Click here