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.

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.

ExampleEdit & Run

Use symmetric_difference() 

A = {1, 2, 3, 4}
B = {3, 4, 5, 6}

result = A.symmetric_difference(B)
print(result)
copy
Output:
{1, 2, 5, 6} [Finished in 0.010654849000275135s]

With other iterables 

As earlier mentioned, the argument to the symmetric_difference() method may be a set or any other type of iterable. 

ExampleEdit & Run

with list

A = {1, 2, 3, 4}
B = [3, 4, 5, 6] #a list

result = A.symmetric_difference(B)
print(result)
copy
Output:
{1, 2, 5, 6} [Finished in 0.010092556476593018s]
ExampleEdit & Run

with tuple

A = {'Python', 'Java', 'C++', 'C'}
B = ('Ruby', 'Python', 'C', 'Javascript') #a tuple

result = A.symmetric_difference(B)
print(result)
copy
Output:
{'Javascript', 'Ruby', 'C++', 'Java'} [Finished in 0.022592530585825443s]

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.  

Syntax:
set_a ^ set_b
copy
ExampleEdit & Run
A = {'Python', 'Java', 'C++', 'C'}
B = {'Ruby', 'Python', 'C', 'Javascript'}

result = A ^ B
print(result)
copy
Output:
{'Ruby', 'Javascript', 'C++', 'Java'} [Finished in 0.0106557821854949s]

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.

ExampleEdit & Run
A = {'Python', 'Java', 'C++', 'C'}
B = ['Ruby', 'Python', 'C', 'Javascript'] #a list

result = A ^ B #error
copy
Output:
Traceback (most recent call last):   File "<string>", line 4, in <module> TypeError: unsupported operand type(s) for ^: 'set' and 'list' [Finished in 0.009668197482824326s]