Skip to content

Python intersection of two sets | Example code

  • by

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 a new set containing 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}

Difference 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.

Please comment if you have any doubts or suggestions on this Python set tutorial.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

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

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading