Python Set symmetric_difference_update() method



The Python Set symmetric_difference_update() method is used to modify a set by removing elements that are common to both sets and inserting elements that are exclusive to either set. It updates the set calling the method with the symmetric difference of itself and another set.

It does not return a new set but modifies the original set in place. This operation is similar to the XOR operation in boolean logic. It efficiently handles the union of two sets while excluding the intersection which results in a set containing elements exclusive to either set.

Syntax

Following is the syntax and parameters of Python Set symmetric_difference_update() method −

set.symmetric_difference_update(other)

Parameter

This method accepts another set or, any iterable and the elements of this iterable/set are compared with the current set object to find the symmetric difference.

Return value

This method does not return any value.

Example 1

Following is the basic example of python set symmetric_difference_update() method, which set1 is updated to include elements that are only in either set1 or set2 but not in both −

set1 = {1, 2, 3}
set2 = {3, 4, 5}

set1.symmetric_difference_update(set2)
print(set1)   

Output

{1, 2, 4, 5}

Example 2

Here in this example we are checking the symmetric difference of the set with an empty set and updating the result using the symmetric_difference_update() method −

set1 = {1, 2, 3}
set2 = set()

set1.symmetric_difference_update(set2)
print(set1)  

Output

{1, 2, 3}

Example 3

Below is the example in which we are checking for all elements, which are common in both sets −

set1 = {1, 2, 3}
set2 = {1, 2, 3}

set1.symmetric_difference_update(set2)
print(set1)  

Output

set()

Example 4

Here in this example we will check if there are no common elements between the two sets then set1 is updated to include all elements from both sets −

set1 = {1, 2, 3}
set2 = {4, 5, 6}

set1.symmetric_difference_update(set2)
print(set1)  

Output

{1, 2, 3, 4, 5, 6}
python_set_methods.htm
Advertisements