Python Set union() Method
The union() method returns a new set containing unique elements from the orignal set and all other specified sets (or iterables).
Syntax
set.union(*iterables)
Parameter
iterables: One or more iterables (sets, lists, strings) to combine with the set.
Return Value
Returns a new set containing all unique elements from all sets. It doesn’t modify the original set.
Example 1: Union of two sets
set1 = {1, 2, 3}
set2 = {3, 4, 5}
result = set1.union(set2)
print(result) # Output: {1, 2, 3, 4, 5}
Example 2: Union of multiple sets
You can pass multipe sets, separated by commas, as arguments to the union() method.
set1 = {1, 2, 3}
set2 = {3, 4, 5}
set3 = {6, 7, 8}
result = set1.union(set2, set3)
print(result) # Output: {1, 2, 3, 4, 5, 6, 7, 8}
Example 3: Union with other data types (list and tuples)
You can also pass other iterables, such as lists or tuples, to the union() method.
my_set = {1, 2, 3}
my_list = [4, 5, 6]
my_tuple = (7, 8, 9)
result = my_set.union(my_list, my_tuple)
print(result) # Output: {1, 2, 3, 4, 5, 6, 7, 8, 9}
The | Operator
The | is a shorthand for set union, but it only works with sets.
For example:
set1 = {1, 2, 3}
set2 = {4, 5, 6}
set3 = {7, 8, 9}
result = set1 | set2 | set3
print(result) # Output: {1, 2, 3, 4, 5, 6, 7, 8, 9}