Skip to content

What is Python set intersection operator | Code

  • by

Set intersection means getting a new set with elements that are common to all sets. In Python intersection has & operator. You can also use the intersection() method to intersect two or more sets:

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

Example use the set intersection operator in Python

Simple example code.

set1 = {'Python', 'Java', 'C++'}
set2 = {'C#', 'Java', 'C++'}

res = set1 & set2

print(res)

Output:

What is Python set intersection operator

Here’s an example to demonstrate how the intersection operator works:

set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7}
set3 = {5, 6, 7, 8, 9}

intersection = set1 & set2 & set3
print(intersection)

In the above example, the intersection of set1, set2, and set3 is computed using the & operator. The resulting set contains only the common element, which is 5 in this case.

Note: the sets being intersected can have any number of elements, and the order of the elements does not matter. The intersection operator returns a new set containing only the elements that are present in all the sets being intersected. If there are no common elements, an empty set is returned.

Do comment if have any questions or suggestions on this Python operator topic.

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