Python Sets symmetric_difference()

symmetric_difference() in Python Sets

 

The symmetric difference of two sets A and B, written as A ^ B is a set which contains all elements of set A and B that are not in their intersection ( common in both set A and B ).

^ symbol denotes symmetric difference of sets.

Python Sets symmetric_difference()
Let us understand this with an example :
  • A = { 1, 2, 3, 4, 5, 6, 7, 8 }
  • B = { 3, 6, 9, 12, 15 }
  • A ^ B = { 1, 2, 4, 5, 7, 8, 9, 12, 15 }

Explanation :

  • A ∪ B = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 12, 15 }
  • A ∩ B = { 3, 6 }
  • A ^ B = (A ∪ B) – (A ∩ B)
  • A ^ B = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 12, 15 } – { 3, 6 }
  • A ^ B = { 1, 2, 4, 5, 7, 8, 9, 12, 15 }

Syntax :


set1.symmetric_difference(set2)
OR
set1 ^ set2



Return Type :

The symmetric_difference() method returns symmetric difference between two sets, which is equal to the elements present in either of the two sets, but not common to both the sets.

Using the ^ Operator


#symmetric difference of sets using ^ operator

#example 1
set1 = {‘P’‘Y’‘T’‘H’‘O’‘N’ }
set2 = {‘C’‘O’‘D’‘I’‘N’‘G’ }
#common elements {‘O’,’N’} will be removed
print( set1 ^ set2 )

#example 2
A = { 24681012 }
B = { 3691215 }
#common elements {6, 12} will be removed
print( A^B )


Output :

{'G', 'H', 'I', 'P', 'Y', 'T', 'C', 'D'}
{2, 3, 4, 8, 9, 10, 15}

Using symmetric_difference() method


#symmetric difference of sets using symmetric_difference() method

#example 1
set1 = {‘P’‘Y’‘T’‘H’‘O’‘N’ }
set2 = {‘C’‘O’‘D’‘I’‘N’‘G’ }
#common elements {‘O’,’N’} will be removed
print( set1.symmetric_difference(set2) )

#example 2
A = { 2468 , 10 }
B = { 123456 }
#common elements {2, 4, 6} will be removed
print( A.symmetric_difference(B) )


Output :

{'G', 'H', 'I', 'P', 'Y', 'T', 'C', 'D'}
{1, 3, 5, 8, 10}