Python Set Intersection()

Intersection() of a Set

 

The intersection() of two or more sets returns a set that contains all common items from all the sets.

The result set contains a distinct element that is, the item that is present in all sets, the result will contain only one appearance of this item.

the symbol denotes the intersection of sets.

Python Set Intersection()

Let us understand this concept with an example, suppose there are two sets A and B, we have to find A B.

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

B = { 1, 3, 5, 7, 9 }

A B = { 1, 3, 5 }

Syntax :


set1.intersection(set2,set3,…)

The parameter can be only one or more. You can compare as many sets as you like. Separate each set with a comma.

Return Type :

The intersection() method returns a new set with all the common elements from the set and all other sets (passed as an argument).

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

Using the & operator


#intersection 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 :

{'N', 'O'}

{12}

Using intersection() function


#intersection of sets using intersection() method

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

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


Output :

{'N', 'O'}

{12}

Intersection of three sets

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

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

A ∩ B ∩ C  =  (A ∩ B) ∩ C  =  A ∩ (B ∩ C)  =  (A ∩ C) ∩ B


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

#A & B
x=A.intersection(B)
print(“A intersectionb B : “,x)

#A & C
y=A.intersection(C)
print(“A intersectionb C : “,y)

#B & C
z=B.intersection(C)
print(“B intersectionb C : “,z)

#( A & B ) & C = A & B & C
print(“( A & B ) & C  : “,x.intersection(C))

#( A & C ) & B = A & B & C
print(“( A & C ) & B  : “,y.intersection(B))

# A & ( B  & C ) = A & B & C
print(“A & ( B  & C ) : “,z.intersection(A))

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



Output :

A intersectionb B :  {18, 12, 6}
A intersectionb C :  {4, 8, 12, 16, 20}
B intersectionb C :  {24, 12}

(A & B) & C :  {12}
(A & C) & B :  {12}
A & (B & C) :  {12}
A & B & C   :  {12}