Python Tutorial Python Advanced Python References Python Libraries

Python Set - symmetric_difference_update() Method



The Python symmetric_difference_update() method is used to update the set by adding all elements which are not present in the given set but present in specified set and deleting all elements which are common to both sets. This method takes only argument and can take a set or an iterable as an argument.

The below figure depicts two sets called A = {10, 20, 30, 40, 50, 60} and B = {40, 50, 60, 70}. As 40, 50 and 60 are common elements between A and B, hence intersection of these sets will be {40, 50, 60}. Similarly, union of these two sets will be {10, 20, 30, 40, 50, 60, 70}. The symmetric_difference_update() method can be expressed as:

  • A.symmetric_difference_update(B) is same as A = (AUB) - (AꓵB) = {10, 20, 30, 70}
  • B.symmetric_difference_update(A) is same as A = (BUA) - (BꓵA) = {10, 20, 30, 70}
Intersection of Sets

Syntax

set.symmetric_difference_update(iterable)

Parameters

iterable Required. specify set or iterable to compute the symmetric_difference set and replace the given set with symmetric_difference set.

Return Value

None.

Example: Symmetric difference update using set as an argument

In the example below, two sets called SetA and SetB are taken to compute Symmetric difference set and replace the SetA with symmetric_difference set.

SetA = {10, 20, 30, 40, 50, 60}
SetB = {40, 50, 60, 70}

SetA.symmetric_difference_update(SetB)
print(SetA)

The output of the above code will be:

{20, 70, 10, 30}

Example: Symmetric difference update using iterable as an argument

In the example below, a set called SetA and a list called ListB are taken to compute Symmetric difference set and replace the SetA with symmetric_difference set.

SetA = {10, 20, 30, 40, 50, 60}
ListB = [40, 50, 50, 60, 60, 70]

SetA.symmetric_difference_update(ListB)
print(SetA)

The output of the above code will be:

{20, 70, 10, 30}

❮ Python Set Methods