Python Tutorial Python Advanced Python References Python Libraries

Python Set - difference() Method



The Python difference() method returns 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.

Return Value

Returns a set which contains all elements of the given set but not the element of specified sets or iterables.

Example: Difference set using set as an argument

In the example below, 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))

The output of the above code will be:

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

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 example below, 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))

The output of the above code will be:

{10, 20, 30}

❮ Python Set Methods