Python: Intersection of Sets

Intersection of two given sets is the largest set which contains all the elements that are common to both the sets. The returned set contains only items that exist in both sets, or in all sets if the comparison is done with more than two sets.

This method returns a new set with elements that are common to all sets.

Syntax:

set.intersection(set1, set2 ... etc)

Parameters:

It takes any number of sets, which can be given.

Returns:

  • It returns a set, which has the intersection of all sets(set1, set2, set3…) with set1.
  • It returns a copy of set1 only if no parameter is passes.

Example:

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

print('A ∩ B =', A.intersection(B))
print('A ∩ C =',A.intersection(C))
print('B ∩ C =',B.intersection(C))

Output:

A ∩ B = {3}
A ∩ C = set()
B ∩ C = {5}
Tags