Skip to content

Python set intersection operator | Example code

  • by

Python has a & operator to intersect two or more sets. Python set intersection operator only allows sets.

set1 & set2

Note: Use the set intersection() method can accept any iterables, like strings, lists, and dictionaries.

Python set intersection operator example

Simple example code set intersection with operator ( & ).

set1 = {2, 4, 5, 6}
set2 = {4, 6, 7, 8}

res = set1 & set2

print(res)

Output:

Python set intersection operator

Note: the set intersection operator (&) will raise an error if you use it with iterables.

Let’s try set intersect with a list using operator

numbers = {1, 2, 3}
scores = [2, 3, 4]

res = numbers & scores

print(res)

Output: TypeError: unsupported operand type(s) for &: ‘set’ and ‘list’

Solution: Use set intersection() method.

res = numbers.intersection(scores)

Do comment if you have any doubts or suggestions on this Python set topic code.

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