Python intersection of two sets | Example code

Use set intersection() to find the intersection of two sets in Python. Even you can use multiple sets for it. You will get a new set with elements that are common to all sets.

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

Python intersection of two sets example

Simple example code get new set contains only items that exist in both sets.

set1 = {2, 3, 5, 1}
set2 = {1, 3, 5}

res = set1.intersection(set2)

print(res)

Output:

Python intersection of two sets

Set Intersection Using & operator

Using AND operator, You can do a set of intersections without using the method.

set1 = {2, 3, 5, 1}
set2 = {1, 3, 5}

res = set1 & set2

print(res)

OR

res = set1 and set2

Output: {1, 3, 5}

Ddifference between Set intersection() method vs set intersection operator (&)

Answer: The set intersection operator only allows sets while the set intersection() method can accept any iterables, like strings, lists, and dictionaries.

Do comment if you have any doubts and suggestions on this Python set tutorial.

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.