Python Set intersection_update() Method

Updates the set by removing the items that are not common

Usage

The intersection_update() method updates the set by removing the items that are not common to all the specified sets.

You can specify as many sets as you want, just separate each set with a comma.

If you don’t want to update the original set, use intersection() method.

Syntax

set.intersection_update(set1,set2…)

Python set intersection_update() method parameters
ParameterConditionDescription
set1, set2…OptionalA comma-separated list of one or more sets to search for common items in

Basic Example

Example: Remove items that are not common to both A & B

A = {'red', 'green', 'blue'}
B = {'yellow', 'red', 'orange'}

A.intersection_update(B)
print(A)

Output:

{'red'}

Venn Diagram:

Set intersection

Equivalent Operator &=

You can achieve the same result by using the &= augmented assignment operator.

Example:

A = {'red', 'green', 'blue'}
B = {'yellow', 'red', 'orange'}

A &= B
print(A)

Output:

{'red'}

intersection_update() Method with Multiple Sets

Multiple sets can be specified with either the operator or the method.

Example:

# by method
A = {'red', 'green', 'blue'}
B = {'yellow', 'orange', 'red'}
C = {'blue', 'red', 'black'}

A.intersection_update(B,C)
print(A)
# by operator
A = {'red', 'green', 'blue'}
B = {'yellow', 'orange', 'red'}
C = {'blue', 'red', 'black'}

A &= B & C
print(A)

Output:

{'red'}