Python Reference ยท Dictionaries and Sets
Python set.discard() method
Reference for Python set.discard(): remove an element if it is present without raising KeyError, compared with remove() and pop(), with examples.
The discard() method removes an element from a set if it is there. If the element is missing, nothing happens and no error is raised. It works in place and returns None.
This forgiving behavior is the difference from remove(), which raises KeyError for a missing element. Choose discard() when "make sure it is gone" is all you want to say.
tags = {"a", "b"} tags.discard("a") tags.discard("z") # no error
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.discard(elem)
| Name | Description |
|---|---|
elem |
The element to remove. |
Return value: None, whether or not the element was present.
Raises: TypeError if elem is unhashable (a plain set is the one exception, see notes).
Usage notes
- It mutates the set. Frozen sets do not have it.
- Absent is not an error. Use
set.remove()when a missing element is a bug you want to hear about. - Unhashable arguments raise
TypeError, with one convenience: passing a plainsetis treated as the equivalentfrozensetfor the lookup, sos.discard({1, 2})removes a matching frozenset element if present. - No return value to test. To know whether anything was removed, check
elem in sfirst or compare lengths. - Equality rules:
1,1.0andTrueare the same element, sodiscard(1.0)removes1. - Removing many items: use
set.difference_update()rather than a loop.
Related
set.remove(),set.pop(),set.add(),set.clear()- Lessons: Sets