Python - Set union() Method

The Python set union() method is used to return a set which contains all elements of two or more sets. This method can take any number of sets or iterables to compute the union set. Please note that, this method does not change the original set.

The below figure depicts two sets called A = {10, 20, 30, 40, 50, 60} and B = {50, 60, 70, 80}. As the union set contains all elements of the two given sets, hence the union of these sets will be {10, 20, 30, 40, 50, 60, 70, 80}. The union() method can be expressed as:

• A.union(B) is same as AUB
• B.union(A) is same as BUA
• A.union(B, C) is same as AUBUC

Syntax

set.union(iterable(s))


Parameters

 iterable(s) Optional. specify set(s) or iterable(s) to compute union set.

Example: Union set using set as an argument

In the below example, two sets called SetA and SetB are taken to compute union of these sets using python union() method.

SetA = {10, 20, 30, 40, 50, 60}
SetB = {50, 60, 70, 80}

print(SetA.union(SetB))


Output

{10, 20, 30, 40, 50, 60, 70, 80}


Example: Union set using set and iterable as arguments

The union() method can take any numbers of sets or iterables to return union set. In the below example, the union() method is used with SetA, SetB and ListC to return a set containing all elements of these three objects.

SetA = {10, 20, 30, 40, 50, 60}
SetB = {40, 50, 90}
ListC = [40, 90, 100]
print(SetA.union(SetB, ListC))


Output

{10, 20, 30, 40, 50, 60, 90, 100}