Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท Dictionaries and Sets

Python set.intersection_update() method

Reference for Python set.intersection_update(): keep only elements found in every other iterable, modifying the set in place, with the &= operator and pitfalls.

The intersection_update() method keeps only the elements that are present both in the set and in all the given iterables, and removes everything else. It changes the set in place and returns None. It is the in-place counterpart of set.intersection().

Use it to narrow a set step by step, for example filtering candidates by several constraints.

Python
s = {1, 2, 3, 4}
s.intersection_update({2, 4, 6})   # s is now {2, 4}

Try it

Python Narrowing candidates

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python Operator form and the empty call

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Syntax

Python
set.intersection_update(*others)
set &= other
Name Description
*others Zero or more iterables. Only elements present in all of them stay in the set.
other For &=, the right side must be a set or frozenset.

Return value: None.

Raises: TypeError if an argument is not iterable or contains unhashable elements.

Usage notes

  • It mutates the set and anything sharing the reference. Copy first with set.copy() if you need the original.
  • It can empty the set. With no common elements, the result is set().
  • Missing arguments mean no change. s.intersection_update() does nothing.
  • Method versus operator. The method accepts any iterable; &= requires a set.
  • Not on frozenset. Use intersection() for a new frozen result.
  • Return value trap. s = s.intersection_update(x) makes s equal to None.