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.
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.
set1.difference_update(set2, ...)
copy
The method modifies set1
by removing all the elements that are also present in set2
.
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.
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.