The symmetric difference of two sets A
and B
is the set of elements that are in either A
or B
, but not in both. It is denoted by A △ B
.
For example if you have sets 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 sets but not in both sets.
In Python, to get the symmetric difference of two sets, we use the set.symmetric_difference()
method. The method has the following syntax.
set_a.symmetric_difference(set_b)
copy
The argument set_b
can be a set or any other type of iterable such as lists, tuples, etc.
The method returns a new set that is the symmetric difference of the current set and the one given as argument.
With other iterables
As earlier mentioned, the argument to the symmetric_difference()
method may be a set or any other type of iterable.
Using the ^
operator instead
The caret(^
) is the operator version of the symmetric_difference()
method. It also returns a new set that is the symettric difference of the two set operand.
set_a ^ set_b
copy
Unlike with the method, this approach requires both operands to be sets not just any other iterables. Using other iterable for the second operand will raise a TypeError
exception.