Joining Sets

You can join two or more sets using methods like union(), update(), or set operators.

Using union()

Example: Joining Two Sets

# Joining sets using union()
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1.union(set2)
print("Union Set:", union_set)

Output

Union Set: {1, 2, 3, 4, 5}

Using update()

Example: Updating a Set with Another Set

# Updating a set
set1.update(set2)
print("Updated Set1:", set1)

Output

Updated Set1: {1, 2, 3, 4, 5}

Using Set Operators

Example: Intersection and Difference

# Set intersection and difference
intersection_set = set1 & set2
difference_set = set1 - set2
print("Intersection Set:", intersection_set)
print("Difference Set:", difference_set)

Output

Intersection Set: {3, 4, 5}

Difference Set: {1, 2}

Explanation: The union() method returns a new set containing all unique items from both sets. The update() method adds items from one set to another. Set operators like & (intersection) and - (difference) perform mathematical set operations.