Python Set intersection()

Python Set x.intersection(y) method returns a new set with the elements that are present in both x and y.

In this tutorial, we will learn the syntax of set.intersection() method and go through examples covering different scenarios for the arguments that we pass to intersection() method.

Syntax

The syntax of set.intersection() is

set.intersection(other)

where

ParameterDescription
otherA set.
ADVERTISEMENT

Examples

1. Intersection of sets x, y

In the following program, we will take two sets: x, y; and find the intersection of the sets.

Python Program

x = {'apple', 'banana', 'cherry'}
y = {'banana', 'mango', 'apple', 'guava'}
result = x.intersection(y)
print(result)
Try Online

Program Output

{'banana', 'apple'}

2. Intersection with an empty set

In the following program, we will take two sets: x, y; and find the intersection of the sets. We take the set y an empty set. The result must be an empty set.

Python Program

x = {'apple', 'banana', 'cherry'}
y = set()
result = x.intersection(y)
print(result)
Try Online

Program Output

set()

Conclusion

In this Python Tutorial, we learned about Python set method intersection(). We have gone through the syntax of intersection() method, and its usage with example programs.