Python – Get Union of Two or more Sets

In this tutorial, we will look at how to get the union of two or more sets in Python with the help of some examples.

venn diagram of union of two sets

The union operation between two sets results in a set containing the unique elements of both the sets. The following is an example.

Diagram showing union operation between two sets.

You can see that the result of union of sets A and B is a set containing all the elements from both these sets (1, 2, 3, 4).

Python comes with a built-in set data structure to implement a set. It also has a number of additional functions to help you with common operations on sets such as union, intersection, difference, etc.

To get the union between two sets in Python, you can use the set union() function. The following is the syntax:

# union of two sets - a and b
a.union(b)

It returns a new set containing elements resulting from the union of the elements from set a and b. Let’s see an example.

# create two sets
a = {1,2,4}
b = {3,5,7,1}
# union between two sets
a.union(b)

Output:

{1, 2, 3, 4, 5, 7}

You can see that the resulting set contains all the elements from both the sets.

To get the union of more than two sets at once, you can use the following syntax.

# union of more than two sets, for example, a,b,c,d
a.union(b,c,d)

Pass the sets (apart from the first one) as arguments to the union() function. It returns a set containing all the elements from all the sets involved in the union operation. Let’s look at an example.

# create four sets
a = {1,2}
b = {8,9}
c = {0,1,5}
d = {4,3}
# union between the above four sets
a.union(b,c,d)

Output:

{0, 1, 2, 3, 4, 5, 8, 9}

We get the union with elements from all the sets.

Alternatively, you can also use the | operator to get the union between two more sets. For example –

# alternative method
e = a | b | c | d
print(e)

Output:

{0, 1, 2, 3, 4, 5, 8, 9}

We get the same result as above.

You might also be interested in –


Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.


Tags:

Leave a Reply

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