Python - Set difference() Method


Advertisements

The Python set difference() method is used to return a set which contains all elements of the given set but not the element of specified sets or iterables. This method can take any number of sets or iterables as arguments to compute the difference set. Please note that, this method does not change the original 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() method can be expressed as:

  • A.difference(B) is same as A-B
  • B.difference(A) is same as B-A
  • A.difference(B, C) is same as A-B-C
difference of Sets

Syntax


set.difference(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 using python difference() method.

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

print(SetA.difference(SetB))
print(SetB.difference(SetA))

Output

{10, 20, 30, 40}
{70, 80}

Example: Difference set using set and iterable as arguments

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

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

Output

{10, 20, 30}

Sets Methods




Advertisements