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.
colors = {"red", "green"} colors.remove("red")
Try it
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.
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
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, sos = s.remove(x)replaces your set withNone. - The
KeyErrorcarries 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 because1 == 1.0and 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 overlist(s)or build a new set with a comprehension. - Remove many elements with
difference_update()ors -= other.
Related
set.discard(),set.pop(),set.clear(),set.difference_update()- Lesson: Sets