Python - Set difference_update() Method


Advertisements

The Python set difference_update() method is used to delete all elements of the given set which are present in the specified sets or iterables. This method can take any number of sets or iterables as arguments to compare with the given set.

The below figure depicts two sets called A = {10, 20, 30, 40, 50, 60} and B = {50, 60, 70, 80}. A-B = {10, 20, 30, 40} and B-A = {70, 80} are shown in the figure. Please note that A-B ≠ B-A in set operation. The difference_update() method can be expressed as:

  • A.difference_update(B) is same as A = A-B
  • B.difference_update(A) is same as B = B-A
  • A.difference_update(B, C) is same as A = A-B-C
Difference of Sets

Syntax


set.difference_update(iterable(s))

Parameters

iterable(s) Optional. specify set(s) or iterable(s) to compute difference set.

Example: Difference set using set as an argument

In the below example, two sets called SetA and SetB are taken to compute the difference of these sets and update the original set using python difference_update() method.

SetA = {10, 20, 30, 40, 50, 60}
SetB = {50, 60, 70, 80}
# updates SetA with difference set
SetA.difference_update(SetB)
print(SetA)

SetA = {10, 20, 30, 40, 50, 60}
SetB = {50, 60, 70, 80}
# updates SetB with difference set
SetB.difference_update(SetA)
print(SetB)

Output

{10, 20, 30, 40}

{70, 80}

Example: Difference set using set and iterable as arguments

The difference_update() method can take any numbers of sets or iterables to compute the difference set and update the original set. In the below example, the difference_update() method is used with SetA, SetB and ListC to update SetA with a set containing all elements of original SetA which are not present in SetB and ListC.

SetA = {10, 20, 30, 40, 50, 60}
SetB = {40, 50}
ListC = {60, 100}
SetA.difference_update(SetB, ListC)
print(SetA)

Output

{10, 20, 30}

Sets Methods




Advertisements