Python Set Difference()

Difference() in Python Set

 

The difference() method returns the difference between the sets.

It returns the element which is present in the first set but not present in other sets.

symbol denotes difference of sets.

Python Set Difference()
set 1 = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }
set 2 = { 2, 4, 6, 8, 10, 12, 14, 16, 18 }

Elements which is present in set1 but not present in set2
set 1  –  set 2 = { 1, 3, 5, 7, 9 } 

Elements which is present in set2 but not present in set1
set 2  –  set 1 = { 12, 14, 16, 18 }

Syntax :


#set1 – set2
set1.difference(set2)

#set2 – set1
set2.difference(set1)


Return Type :

The difference method returns a new set having all the elements of set1 which is not present in set2.

If the argument is not passed to the intersection(), it returns a shallow copy of the set.

Using the & operator


#difference of sets using – operator

#example 1
set1 = {‘P’‘Y’‘T’‘H’‘O’‘N’ }
set2 = {‘C’‘O’‘D’‘I’‘N’‘G’ }
print( set1 – set2 )

#example 2
A = { 2468101112 }
B = { 3691215 }
C = { 481216 }
print( A – B – C )



Output :

{'Y', 'P', 'T', 'H'}

{11, 2, 10}

Using intersection() function


#difference of sets using difference() method

#example 1
set1 = {‘P’‘Y’‘T’‘H’‘O’‘N’ }
set2 = {‘C’‘O’‘D’‘I’‘N’‘G’ }
print( set1.difference(set2) )

#example 2
A = { 2468 , 101214161820 }
B = { 36912151821242730 }
C = { 481216202428323640 }
print( A.difference(B,C) )


Output :

{'Y', 'P', 'T', 'H'}

{11, 2, 10}

Difference of three sets

A , B, C are three sets having some elements.

Approach:
  • First Calculate Difference of first two sets (A – B) and store it in any set say X.
  • Then find difference of X with the third set i.e. (X – C).

A – B – C  =  (A – B) – C  =  A – (B – C)


#difference of three sets
A = { 2468 , 101214161820 }
B = { 36912151821242730 }
C = { 481216202428323640 }

#A – B
x=A.difference(B)
print(“A – B          : “,x)

#( A – B ) – C = A – B – C
print(“(A – B) – C  : “,x.difference(C))

#A & B & C
print“A – B – C    : “,A.difference(B,C) )


Output :

A - B          :  {2, 4, 8, 10, 14, 16, 20}
(A - B) - C    :  {2, 10, 14}
A - B - C      :  {2, 10, 14}