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)
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.
Use symmetric_difference()
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
result = A.symmetric_difference(B)
print(result)
With other iterables
As earlier mentioned, the argument to the symmetric_difference()
method may be a set or any other type of iterable.
with list
A = {1, 2, 3, 4}
B = [3, 4, 5, 6] #a list
result = A.symmetric_difference(B)
print(result)
with tuple
A = {'Python', 'Java', 'C++', 'C'}
B = ('Ruby', 'Python', 'C', 'Javascript') #a tuple
result = A.symmetric_difference(B)
print(result)
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
A = {'Python', 'Java', 'C++', 'C'}
B = {'Ruby', 'Python', 'C', 'Javascript'}
result = A ^ B
print(result)
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.
A = {'Python', 'Java', 'C++', 'C'}
B = ['Ruby', 'Python', 'C', 'Javascript'] #a list
result = A ^ B #error