Skip to main content

union()

The union() function in Python is a method of the Set data type that returns a new set containing all the elements present in the original set as well as the elements from one or more other sets. It performs a union operation on sets, which results in a set that contains all unique elements from the original set and the other set(s).

Parameter Values

This function does not accept any parameters.

Return Values

The union() method in Python can return a new set with all distinct elements.

How to Use union() in Python

Example 1:

The union() method returns a new set with elements from both the original set and another set.

set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1.union(set2)
print(union_set) # Output: {1, 2, 3, 4, 5}
Example 2:

The union() method can also take multiple sets as arguments to perform the union operation.

set1 = {1, 2, 3}
set2 = {3, 4, 5}
set3 = {5, 6, 7}
union_set = set1.union(set2, set3)
print(union_set) # Output: {1, 2, 3, 4, 5, 6, 7}
Example 3:

The union() method does not modify the original sets, it returns a new set with the combined elements.

set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1.union(set2)
print(set1) # Output: {1, 2, 3}
print(set2) # Output: {3, 4, 5}