Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages

Python Set Union

Union basically represents all the distinct elements of the corresponding sets altogether.

Python Set union() method finds the union of the sets and represents a new set which contains all the items from the corresponding input sets.

Note: If a set contains an element that appears more than once, then the output represented contains only a single appearance of the particular element.

Syntax:

set1.union(set2, set3,......, setN)

Basic understanding of Python Set Union

info = {'Safa', 'Aman', 'Divya', 'Elen'}
info1 = {'Safa', 'Aryan'}

print(info.union(info1))

Output:

{'Aman', 'Safa', 'Divya', 'Aryan', 'Elen'}

Python Set Union using “|” operator

The “|” operator can also be used to find the union of the input sets.

info = {'Safa', 'Aman', 'Diya'}
info1 = {'Varun', 'Rashi', 54 }

print(info | info1)

Output:

{'Diya', 'Aman', 'Safa', 54, 'Varun', 'Rashi'}

Union of Multiple Python Sets

Either of the following techniques can be used to find the union of multiple sets:

  • Passing multiple sets as arguments to the union() method
  • By creating a chain of union() method calls

1. Union of multiple sets using multiple sets as arguments

info = {12, 14, 15, 17}
info1 = {35, 545}
info2 = {'Safa','Aman'}

print(info.union(info1, info2))

Output:

{'Safa', 17, 545, 35, 'Aman', 12, 14, 15}

2. Union of multiple sets by creating a chain of union() method calls

info = {12, 14, 15, 17}
info1 = {35, 545}
info2 = {'Safa','Aman'}

print(info.union(info1).union(info2))


Output:

{'Aman', 17, 545, 35, 'Safa', 12, 14, 15}

Conclusion

Thus, in this article, we have understood and implemented ways to find the union of sets in Python.


References

Leave a Reply

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