Python Set intersectionupdate

Python Set x.intersection_update(y) method removes the elements from the set x that are not present in y. In other words, updates set x with the intersection of x and y.

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

Syntax

The syntax of set.intersection() is

set.intersection_update(other)

where

Parameter Description
other A set.

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, and update x with the resulting set.

Python Program

x = {'apple', 'banana', 'cherry'}
y = {'banana', 'mango', 'apple', 'guava'}
x.intersection_update(y)
print(x)

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()
x.intersection_update(y)
print(x)

Program Output

set()

Conclusion

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