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.

ExampleEdit & Run

using symmetric_difference() 

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

result = A.symmetric_difference(B) #creates a new set
print(result)
Output:
{1, 2, 5, 6}[Finished in 0.010478665819391608s]

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:

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.

ExampleEdit & Run

 using symmetric_difference_update()

set_a = {1, 2, 3, 4}
set_b = {3, 4, 5, 6}

set_a.symmetric_difference_update(set_b) #modifies set_a

print(set_a)
Output:
{1, 2, 5, 6}[Finished in 0.009592049987986684s]

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.

ExampleEdit & Run

with list

A = {'Python', 'Java', 'C++', 'Ruby'} #set
B = ['HTML', 'Python', 'Java', 'Javascript'] #list

A.symmetric_difference_update(B) #modifies A
print(A)
Output:
{'HTML', 'Javascript', 'Ruby', 'C++'}[Finished in 0.00935616111382842s]

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. 

Syntax:
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.

ExampleEdit & Run

Using ^= operator 

set_a = {'Python', 'Java', 'C++', 'Ruby'} #set
set_b = {'HTML', 'Python', 'Java', 'Javascript'} #set

set_a ^= set_b  #modifies set_a
print(set_a)
Output:
{'HTML', 'Javascript', 'Ruby', 'C++'}[Finished in 0.009354117093607783s]