How to Create A Union Of Sets In Python

In this tutorial, we will be seeing how to create a union of sets in python. A set in python is similar in notion to that in mathematics. In Python, we have to use curly brackets to write sets. The following method can be used to create a union of two or more sets.

Create A Set in Python

Sets are defined using curly brackets ‘{}’.

set1 = {1,2,2,3}
print(set1)

Here, we are creating a set named set1 with elements {1,2,2,3}. Then we print the set using print(set_name). As a set has no duplicate elements, the output will be:

{1, 2, 3}

Union of Sets in Python

In Python, union() allows arbitrary number of arguments. The union() method returns the union of all the sets passed as parameters.
There are multiple ways to create the union of two or more sets. So, let’s see the code now.

set1 = {1,2,2,3,4}
set2 = {2,4,5,6,6}
set3 = {4,7,6,9,8,8}

print("Using | operator: ", set1|set2|set3)
print("Using 'set' module: ", set.union(set1, set2, set3))
print("Using 'set' module(2): ", set1.union(set2, set3))

The ways to find the union of two or more sets are:

1. Using the | operator:
Here, the sets whose union has to be found are separated by | symbol.
2. Using ‘set ‘ module:
The sets whose union has to be found are passed as parameters to set.union().
3. Another way of using ‘set’ module:
The sets whose union is to be found with set1 are passed as parameters to set1.union().

Output

Using | operator: {1, 2, 3, 4, 5, 6, 7, 8, 9}
Using 'set' module: {1, 2, 3, 4, 5, 6, 7, 8, 9}
Using 'set' module(2): {1, 2, 3, 4, 5, 6, 7, 8, 9}

So here it is, a very simple tutorial to understand union of sets in python.