Cover Image for Union of Set in Python
143 views

Union of Set in Python

The Python perform the union operation on sets using the union() method, the | operator, or the union() function. The union of two sets contains all unique elements from both sets. Here’s how you can use these methods:

Using the union() Method:

Python
# Create two sets
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}

# Use the union() method to perform the union operation
union_result = set1.union(set2)

# Display the result
print(union_result)

Using the | Operator:

Python
# Create two sets
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}

# Use the | operator to perform the union operation
union_result = set1 | set2

# Display the result
print(union_result)

Using the union() Function:

You can also use the built-in union() function, which takes one or more sets as arguments and returns their union as a new set:

Python
# Create two sets
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}

# Use the built-in union() function to perform the union operation
union_result = set.union(set1, set2)

# Display the result
print(union_result)

All three methods will give you the same result:

Plaintext
{1, 2, 3, 4, 5, 6}

The resulting set contains all unique elements from both set1 and set2. Remember that sets in Python do not allow duplicate elements, so the union operation automatically removes duplicates.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS