In Python, the union() method is used to combine two sets into a new set that contains all the unique elements from both sets. Here's an example:
set1 = {1, 2, 3}set2 = {3, 4, 5}union_set = set1.union(set2)print(union_set) |
Output:
{1, 2, 3, 4, 5} |
In the above code, set1 contains the elements 1, 2, and 3, while set2 contains the elements 3, 4, and 5. The union() method is called on set1, passing in set2 as an argument. The result is a new set, union_set, that contains all the unique elements from both set1 and set2.
Note that the original sets set1 and set2 are not modified by the union() method. The method returns a new set that contains the result of the operation.
Also, you can use the | operator to perform a union operation on two sets like this:
set1 = {1, 2, 3}set2 = {3, 4, 5}union_set = set1 | set2print(union_set) |
Output:
{1, 2, 3, 4, 5} |
The output will be the same as before. The | operator is a shorthand way of performing the union() operation on two sets.