symmetric_difference() of Sets in Python

symmetric_difference() of Sets in Python 

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.

symmetric difference of sets in python

symmetric_difference() of sets

In Python, you can find the symmetric difference of sets using the symmetric_difference() method or the ^ operator. The symmetric difference between two sets contains the elements that are present in either of the sets but not in both sets.

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 }
Python Sets symmetric_difference()

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

Run
#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 = { 2, 4, 6, 8, 10, 12 }
B = { 3, 6, 9, 12, 15 }
#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

Run
#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 = { 2, 4, 6, 8 , 10 }
B = { 1, 2, 3, 4, 5, 6 }
#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}

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription