Python Set intersection() Method Tutorial

In this section, we will learn what the Set intersection() method is and how to use it in Python.

What is Set intersection() Method in Python?

The Python Set intersection() method is used to find the common elements between two Set objects and return those elements as part of a new Set object.

Basically, this method takes one argument and that is a reference to a Set object. Then this method will compare the elements of the Set object that this method is invoked with and the reference Set, and finally it will return those elements that are common in both Sets.

Note: there’s another method called intersection_update() that does the same task. The difference, however, is that the intersection() method returns a new Set object but the intersection_update() method updates the original Set method (the one that invoked the method) and returns no value.

Python Set intersection() Method Syntax:

set.intersection(referenceSet)

Set intersection() Method Parameter:

The method takes one argument and that is a reference to a Set object.

Set intersection() method Return Value

The return value of this method is a new Set object that contains all the common elements between the two Set objects.

Note that if the two Sets didn’t have any common element, then the return value of this method becomes an empty Set.

Example: using python set intersection() method

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

set2 = {1,2,3,4,5,500,600,700}

result = set1.intersection(set2)

print(set1)

print(result)

print(set2)

Output:

{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

{1, 2, 3, 4, 5}

{1, 2, 3, 4, 5, 500, 600, 700}
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies