Python Set intersection_update() Method
The intersection_update() method updates a set in place by keeping only the elements that are common to all specified sets or iterables.
Syntax
set.intersection_update(*others)
Parameters
others: One or more sets (or other iterables like tuples or lists) to find common elements with.
Return Value
Doesn’t return anything. It modifies the set in place.
Examples
Example 1: Intersection update of two sets
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
a.intersection_update(b)
print(a) # Output: {3, 4}
Example 2: Intersection update with multiple sets
You can pass multiple sets, separated by commas, as arguments to the intersection_update() method.
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
c = {3, 4, 8, 9}
a.intersection_update(b, c)
print(a) # Output: {3, 4}
Example 3: Intersection update with different iterable types
You can also pass iterables of different types, such as lists or tuples, as arguments to the intersection_update() method.
a = {1, 2, 3, 4}
b = [3, 4, 5, 6] # a list
c = (3, 4, 8, 9) # a tuple
a.intersection_update(b, c)
print(a) # Output: {3, 4}
The &= Operator
The &= operator is the shorthand for performing a set intersection update.
For example:
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
a &= b
print(a) # Output: {3, 4}
Multiple set intersection
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
c = {3, 4, 8, 9}
a &= b & c
print(a) # Output: {3, 4}