The difference of two sets is the set of elements that are in the first set but not in the second set. This is also referred as set subtraction, it is represented by the  minus(-) symbol.

For example if we have two sets,  A = {0, 1, 2, 3, 4, 5, 6} and B = {0, 2, 4, 6}, then, A - B = {1, 3, 5} .

In Python, the set.difference() method returns a new set that is the difference of the current set and the one given as argument.

ExampleEdit & Run

 using set.difference() 

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

#get the difference
result = set1.difference(set2) #creates a new set.
print(result)
copy
Output:
{1, 3, 5} [Finished in 0.011828639078885317s]

Using difference_update() method

Sets are mutable meaning that elements can be added or removed from the original set.

The difference_update() method also gets the difference of two sets, however, it does not create a new set. It instead modifies the original set by removing the elements that are common in both sets, so that only the unique elements remain.

Syntax:
set1.difference_update(set2, ...)
copy

The method modifies set1 by removing all the elements that are also present in set2.

ExampleEdit & Run
set1 = {0, 1, 2, 3, 4, 5, 6}
set2 = {1, 3, 5}

#get the difference
set1.difference_update(set2) #modifies set1
print(set1)
copy
Output:
{0, 2, 4, 6} [Finished in 0.013774699065834284s]

We can also pass multiple sets as arguments to the difference_update() method and it will update the first set by removing any elements that are also present in the other sets. 

ExampleEdit & Run

pass multiple sets

set1 = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
set2 = {1, 3, 5}
set3 = {6, 7, 8, 9}

set1.difference_update(set2, set3)
print(set1)
copy
Output:
{0, 2, 4} [Finished in 0.010572372004389763s]

Using -= operator

The -= is the operator version of the difference_update() method. Similarly, it removes the common elements from the original set so that only the unique elements remain.

ExampleEdit & Run

using -= operator

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

set1 -= set2 #modifies set1
print(set1)
copy
Output:
{0, 2, 4, 6} [Finished in 0.010158699937164783s]