Python 3 reference · Set Methods
Python Set discard() Method
Remove an element if it is present; do nothing if it isn't. The no-error version of remove().
Python 3 Since 3.0
Syntax
set.discard(elem)
Parameters
| Parameter | Description |
|---|---|
elem |
The element to remove. |
Return value
None.
Examples
s = {"a", "b"}
s.discard("a")
s.discard("z") # no error
print(s)
Output
{'b'}s = {1}
try:
s.remove(2)
except KeyError:
print("remove() raises KeyError")
Output
remove() raises KeyError
Version history
| Version | Change |
|---|---|
| Python 3.0 | Added |
Related
set.remove()· Remove an element from the set. Raises KeyError if it isn't present; use discard() to avoid the error.set.pop()· Remove and return an arbitrary element of the set. Raises KeyError if the set is empty.list.remove()· Remove the first item equal to a value. Raises ValueError if the value is not in the list.- Python Sets · tutorial