Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท Dictionaries and Sets

Python set.difference() method

Reference for Python set.difference(): elements in one set but not in others, the minus operator, accepting any iterable, and why the order of operands matters.

The difference() method returns a new set with the elements of the set it is called on that do not appear in any of the other arguments. Think "A minus B". Neither input is changed.

Unlike the - operator, difference() accepts any iterable as its argument (a list, a string, a range) and can take several at once. Order matters: a.difference(b) and b.difference(a) are different sets.

Python
{1, 2, 3, 4}.difference({2, 4})   # {1, 3}

Try it

Python What is missing?

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 Several arguments and the operator's limit

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(*others)
set - other
Name Description
*others Zero or more iterables. Their elements are removed from the result.
other For the - operator, the right side must itself be a set or frozenset.

Return value: a new set. With no arguments it is a copy of the original.

Raises: TypeError if an argument is not iterable, or if an element is unhashable (for example a list of lists).

Usage notes

  • It does not mutate. To update the set itself, use set.difference_update() or -=.
  • Order matters. a - b keeps what only a has. For elements that are in exactly one of two sets, use set.symmetric_difference().
  • The method accepts any iterable; the operator requires sets. The method converts non-set arguments to a temporary set first.
  • Several arguments are equivalent to subtracting each in turn.
  • Strings are iterables of characters. {"a", "ab"}.difference("ab") removes "a", not "ab". Wrap a single string in a list.
  • Cost is roughly proportional to the size of the first set when the other arguments are sets.