Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
communitycreator

How does set intersection_update() work in Python?

Hassan Ahmed

The built-in intersection_update() method in Python is used to update a set that is calling the method with the elements it has in common with another set.

Figure 1 uses a Venn diagram to represent the intersection of two sets.

Figure 1: The common elements in Set X and Y, make up the intersection of both sets.
Figure 1: The common elements in Set X and Y, make up the intersection of both sets.

Syntax

x.intersection_update(y)

Parameters and return value

The intersection_update() method requires at least one set to be passed as a parameter. However, it is up to the user to choose how many sets to compare.

In addition, it is important to take note of the fact that this method returns None, and the set that calls the method is simply updated.

Example #1

#Passing two sets as parameters

x = {'Red', 'Blue', 'Purple', 'Orange'}
y = {'Yellow', 'Orange', 'Blue', 'Turquoise'}

x.intersection_update(y)
print(x)

Example #2

#Passing more than two sets as parameters

x = {'Red', 'Blue', 'Purple', 'Orange'}
y = {'Yellow', 'Orange', 'Blue', 'Turquoise'}
z = {'Cyan', 'Pink', 'Blue', 'Lavender', 'Orange'}

x.intersection_update(y,z)
print(x)

RELATED TAGS

python
communitycreator
RELATED COURSES

View all Courses

Keep Exploring