Set union() Method in Python

Python Set union() Method

The union() method is used to create a new set that contains all the unique elements from two or more sets. It returns a set that is a union of all the specified sets, which means it contains elements from all the sets without any duplicates.

Syntax of the union() method:

result_set = set1.union(set2, set3, ...)

Parameters:

  • set1, set2, set3, ...: The sets you want to combine to create the union.

Note that you can provide multiple sets as arguments to the union() method.Example:

# Creating two sets
set1 = {1, 2, 3}
set2 = {3, 4, 5}

# Creating the union of set1 and set2
result_set = set1.union(set2)

print(result_set)  # Output: {1, 2, 3, 4, 5} (the union of both sets without duplicates)

In this example, the union() method is applied to set1 and set2, and it returns a new set that contains all the elements from both sets (1, 2, 3, 4, 5) without any duplicates.

You can also use the | operator to achieve the same result as the union() method:

# Creating two sets
set1 = {1, 2, 3}
set2 = {3, 4, 5}

# Creating the union of set1 and set2 using the | operator
result_set = set1 | set2

print(result_set)  # Output: {1, 2, 3, 4, 5} (same result as using union())

Both methods, union() and | operator, will give you the same result for creating the union of sets. Choose the one that suits your coding style and preference.