Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท Dictionaries and Sets

Python set.difference_update() method

Reference for Python set.difference_update(): remove all elements found in other iterables from a set in place, the -= operator and the None return value.

The difference_update() method removes from a set every element that appears in any of the given iterables. It changes the set in place and returns None. It is the in-place counterpart of set.difference().

Use it when you already own the set and just want to trim it, such as removing processed items from a "to do" set.

Python
todo = {"a", "b", "c"}
todo.difference_update({"b"})   # todo is now {'a', 'c'}

Try it

Python Trimming a set in place

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 aliasing

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.difference_update(*others)
set -= other
Name Description
*others Zero or more iterables. Every element found in them is removed from 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 every other name referring to it. Call set.copy() first to keep the original.
  • Missing elements are fine. Elements of the arguments that are not in the set are ignored, with no KeyError (unlike remove()).
  • No arguments leaves the set unchanged.
  • Method versus operator. The method accepts any iterable; -= requires a set on the right.
  • Not available on frozenset. Use difference() there to get a new object.
  • Return value trap. s = s.difference_update(x) sets s to None.