Python Tutorial Python Advanced Python References Python Libraries

Python Set - intersection() Method



The Python intersection() method returns a set which contains all common elements of two or more sets. This method can take any number of sets or iterables to compute the intersection set. Please note that, this method does not change the original set.

The below figure depicts two sets called A = {10, 20, 30, 40, 50, 60} and B = {50, 60, 70, 80}. As 50 and 60 are common elements between A and B, hence intersection of these sets will be {50, 60}. The intersection() method can be expressed as:

  • A.intersection(B) is same as AꓵB
  • B.intersection(A) is same as BꓵA
  • A.intersection(B, C) is same as AꓵBꓵC
Intersection of Sets

Syntax

set.intersection(iterable(s))

Parameters

iterable(s) Optional. specify set(s) or iterable(s) to compute intersection set.

Return Value

Returns a set which contains all common elements of two or more sets.

Example: Intersection set using set as an argument

In the example below, two sets called SetA and SetB are taken to compute intersection of these sets using python intersection() method.

SetA = {10, 20, 30, 40, 50, 60}
SetB = {50, 60, 70, 80}

print(SetA.intersection(SetB))

The output of the above code will be:

{50, 60}

Example: Intersection set using set and iterable as arguments

The intersection() method can take any numbers of sets or iterables to return intersection set. In the example below, the intersection() method is used with SetA, SetB and ListC to return a set containing all common elements of these three objects.

SetA = {10, 20, 30, 40, 50, 60}
SetB = {40, 50, 90}
ListC = {40, 90, 100}
print(SetA.intersection(SetB, ListC))

The output of the above code will be:

{40}

❮ Python Set Methods