Menu Close

Python Set union() Method

Python set union

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.

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

For More information:- Click here

Python Set symmetric_difference() Method
Python Set update Method

Was this post helpful?

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *