The Union Operation in sets combines two or more sets, returning a new set that contains all the unique elements from the combined sets. In Python, you can perform the union operation using the union()
method or the |
(pipe) operator.
Below is the example:
## Union in Sets
# The union operation in sets combines two or more sets,
# returning a new set that contains all the unique elements from the combined sets
set1 = {1,3,5,7}
set2 = {2,4,6,7,8}
# Using union() method
unionResult = set1.union(set2)
print("Union using union() method:", unionResult)
# Output: Union using union() method: {1, 2, 3, 4, 5, 6, 7, 8}
# Multiple sets union
unionResult = set1.union(set2, set3)
print("Union using union() method:", unionResult)
# Output: Union using union() method: {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}
# Using | (pipe) operator
unionResult = set1 | set2
print("Union using | operator:", unionResult)
# Output: Union using | operator: {1, 2, 3, 4, 5, 6, 7, 8}
Output of above code is:
In the above example, we have two sets, set1
and set2
. The union operation combines the elements from both sets, removing any duplicates, and creates a new set with all the unique elements.
Using the union()
method, we invoke it on one set (set1
) and pass the other set (set2
) as the argument. The union()
method returns a new set that contains all the elements from set1
and set2
.
Using the |
operator, we simply apply the operator between the two sets (set1 | set2
). The operator performs the union operation and returns a new set with the combined elements.
Both approaches yield the same result, which is the union of set1
and set2
, resulting in a set containing the elements {1, 2, 3, 4, 5, 6, 7, 8}
.
The union operation is useful when you want to merge multiple sets together while ensuring that only unique elements are included.