In set theory, the union of a collection of sets is the set of all the elements in the collection of the sets. Following image depicts the set union operations between a collection of sets.
Set Union
Python Set Union
Python set class provides union() function to get the union of a collection of sets. The result is a new set with all the elements from the collection of sets.
Let’s look at some examples of Python set union() function.
1 2 3 4 5 6 7 8 |
set1 = {1, 2, 3, 4} set2 = {2, 3, 5, 6} set3 = {3, 4, 6, 7} print(set1.union(set2)) print(set2.union(set3)) print(set3.union(set1)) |
Output:
1 2 3 4 5 |
{1, 2, 3, 4, 5, 6} {2, 3, 4, 5, 6, 7} {1, 2, 3, 4, 6, 7} <img class="alignnone wp-image-22509 size-full" src="http://all-learning.com/wp-content/uploads/2019/01/Python-Set-Union.png" alt="Python Set Union" width="1200" height="628" /> |
Python Set Union
Union of Multiple Sets
We can create the union of multiple sets through two ways.
- By passing multiple sets as argument in union() function.
- Since union() returns a new set, we can create a chain of union() function calls.
Below code snippet shows above two ways implementation.
1 2 3 4 5 |
print(set1.union(set2, set3)) # OR print(set1.union(set2).union(set3)) |
Output:
1 2 3 4 5 |
{1, 2, 3, 4, 5, 6, 7} {1, 2, 3, 4, 5, 6, 7} <img class="alignnone wp-image-22510 size-full" src="http://all-learning.com/wp-content/uploads/2019/01/Python-Multiple-Sets-Union.png" alt="Python Multiple Sets Union" width="1200" height="628" /> |
Python Multiple Sets Union
You can checkout complete python script and more Python examples from our GitHub Repository.
Reference: Official Documentation