Python Set Union

Filed Under: Python

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

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.


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, 6}
{2, 3, 4, 5, 6, 7}
{1, 2, 3, 4, 6, 7}
Python Set Union

Python Set Union

Union of Multiple Sets

We can create the union of multiple sets through two ways.

  1. By passing multiple sets as argument in union() function.
  2. Since union() returns a new set, we can create a chain of union() function calls.

Below code snippet shows above two ways implementation.


print(set1.union(set2, set3))
#  OR
print(set1.union(set2).union(set3))

Output:


{1, 2, 3, 4, 5, 6, 7}
{1, 2, 3, 4, 5, 6, 7}
Python Multiple Sets Union

Python Multiple Sets Union

You can checkout complete python script and more Python examples from our GitHub Repository.

Reference: Official Documentation

Leave a Reply

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

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