Set symmetric_difference_update() Method in Python

Python Set symmetric_difference_update() Method

The symmetric_difference_update() method is used to modify the original set by keeping only the elements that are unique to each set and not common to both. It updates the original set in place and removes elements that are present in both sets, keeping only the elements that are unique to each set.

Syntax of the symmetric_difference_update() method:

set1.symmetric_difference_update(set2)

Parameters:

  • set1: The original set on which you want to perform the symmetric difference operation.
  • set2: The second set is used for the symmetric difference operation.

Example:

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

# Updating set1 to keep only the elements that are unique to each set
set1.symmetric_difference_update(set2)

print(set1)  # Output: {1, 2, 3, 6, 7, 8} (set1 is modified to contain unique elements from both sets)

In this example, the symmetric_difference_update() method is applied to set1, and it uses set2 to calculate the symmetric difference. After the operation, set1 is modified to contain only the elements that are unique to each set (1, 2, 3, 6, 7, 8). Elements 4 and 5, which are present in both set1 and set2, are removed from set1.

You can also use the ^= operator to achieve the same result as the symmetric_difference_update() method:

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

# Updating set1 to keep only the elements that are unique to each set using the ^= operator
set1 ^= set2

print(set1)  # Output: {1, 2, 3, 6, 7, 8} (same result as using symmetric_difference_update())

Both methods, symmetric_difference_update() and ^=, will give you the same result for the symmetric difference operation. Choose the one that suits your coding style and preference.