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.

using symmetric_difference() 

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

result = A.symmetric_difference(B) #creates a new set

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_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 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


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.

with list

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

A.symmetric_difference_update(B) #modifies A

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.

Using ^= operator 

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

set_a ^= set_b  #modifies set_a