The symmetric difference of two sets A
and B
, denoted by A Δ B
, is the set of all elements that are in either set A
or set B
, but not in both.
For example if we have A = {1,2, 3, 4}
and B = {3, 4, 5, 6}
, then A Δ B = {1, 2, 5, 6}
because these are the elements that are in either of the two sets but not in both.
In Python, the set.symmetric_difference()
method creates a new set that is the symmetric difference of the current set and the other set given as argument.
The symmetric_difference_update()
method
Sets are mutable meaning they can be updated after creation.
The symmetric_difference_update()
method updates the original set rather than creating a new set.
It removes any elements that are present in both sets, and will add any elements that are present in the other set but not in the current. It has the following syntax:
set_a.symmetric_difference_update(set_b)
set_b
can be a set or any other iterable object.
The method modifies set_a
so that in the end, it will be the symmetric difference of the original set_a
and set_b
.
Using other iterable objects
As earlier mentioned, the symmetric difference accepts other iterables as arguments. With this approach, the iterable is first transformed into a set before the operations.
Any other type of iterable can be used not just list.
Using ^=
operator instead
The ^=
is the operator version of the symmetric_difference_update()
method. However, the operator requires both operands to be sets unlike the method which allows other form of iterables as its argument.
set_a ^= set_b
Similarly, this operation modifies set_a
so that it becomes the symmetric difference of the original set_a
and set_b
.