Python Tutorial Python Advanced Python References Python Libraries

Python Set - union() Method



The Python union() method returns 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
Union of Sets

Syntax

set.union(iterable(s))

Parameters

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

Return Value

Returns a set which contains all elements of the specified sets.

Example: Union set using set as an argument

In the example below, 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))

The output of the above code will be:

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

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 example below, 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))

The output of the above code will be:

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

❮ Python Set Methods