Python set intersection method | Example code

The Python intersection() method is used to get similar (common) elements between two or more sets. This method actually returns a new set with an element that is common to all sets.

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

Python set intersection example

Simple example code computes the intersection between set1 and set2.

fib = {1, 1, 2, 3, 5, 8}
prime = {2, 3, 5, 7, 11}

res = fib.intersection(prime)
print(res)

Output:

Python set intersection method

Another Example using & operator

You can use & operator to find the intersection of sets.

fib = {1, 1, 2, 3, 5, 8}
prime = {2, 3, 5, 7, 11}

print(fib ^ prime)

Output:

{1, 7, 8, 11}

Example using 3 sets

Compare 3 sets, and return a set with elements that is present in all 3 sets:

result = x.intersection(y, z)

OR

set1 = {2, 4, 5, 6}
set2 = {4, 6, 7, 8}
set3 = {1, 0, 12}

print(set1 & set2 & set3)

Output: set()

Do comment if you have any doubts and suggestions on this Pytho set method.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.