Python Set union() method



The Python Set union() method is used with sets to return a new set containing all the unique elements from the original set and all specified sets. It combines the elements from multiple sets without including duplicates.

We can use the '|' operator as an alternative to this method. The original sets remain unchanged as union() produces a new set. It is commonly used to merge sets and find the overall collection of unique items from multiple sources.

Syntax

Following is the syntax and parameters of Python Set union() method −

set1.union(*others)

Parameter

This function accepts variable number of set objects as parameters.

Return value

This method returns a new set containing all unique elements from the given sets.

Example 1

Following is the basic example of the union() method which returns a new set with all unique elements from set1 and set2 −

set1 = {1, 2, 3}
set2 = {3, 4, 5}

result = set1.union(set2)
print(result)  

Output

{1, 2, 3, 4, 5}

Example 2

Here in this example we are using the union() method with an empty set which gives result as the original set −

set1 = {1, 2, 3}
set2 = set()

result = set1.union(set2)
print(result)  

Output

{1, 2, 3}

Example 3

If all elements are common in both sets then the result is as same as either one of the set. The below is example of it −

set1 = {1, 2, 3}
set2 = {1, 2, 3}

result = set1.union(set2)
print(result)  

Output

{1, 2, 3}

Example 4

Here in this example union() method is used with three sets and the result is a set with all unique elements from all three sets −

set1 = {1, 2}
set2 = {3, 4}
set3 = {4, 5}

result = set1.union(set2, set3)
print(result)  

Output

{1, 2, 3, 4, 5}
python_set_methods.htm
Advertisements