Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท Dictionaries and Sets

Python set.remove() method

Reference for Python set.remove(): delete a specific element from a set, the KeyError when it is missing, how it differs from discard() and unhashable arguments.

The remove() method deletes one element from a set. If the element is not in the set, it raises KeyError, which makes it a good choice when a missing element means a bug in your program.

When the element may or may not be there and you do not care, use discard() instead; it does nothing for a missing element.

Python
colors = {"red", "green"}
colors.remove("red")

Try it

Python Removing and failing

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 remove() versus discard()

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.remove(elem)
Name Description
elem The element to delete. It is compared by equality and hash, like any lookup in a set.

Return value: None.

Raises: KeyError if elem is not in the set. TypeError if elem is unhashable (for example a list).

Usage notes

  • Mutates in place and returns None, so s = s.remove(x) replaces your set with None.
  • The KeyError carries the missing value, so the message shows what you tried to remove.
  • Removes by value, not by position. Sets have no indexes. To take any element out, use pop().
  • Equal values count as the same element. .remove(1.0) works because 1 == 1.0 and their hashes match.
  • Special case: removing a set from a set of frozensets works, because Python converts a temporary set to a frozenset for the lookup.
  • Do not change the set while iterating over it. Python raises RuntimeError: Set changed size during iteration. Iterate over list(s) or build a new set with a comprehension.
  • Remove many elements with difference_update() or s -= other.