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

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

set.discard(elem)

Parameters

ParameterDescription
elem The element to remove.

Return value

None.

Examples

Remove safelyTry it yourself
s = {"a", "b"}
s.discard("a")
s.discard("z")  # no error
print(s)

Output

{'b'}
Compared with remove()Try it yourself
s = {1}
try:
    s.remove(2)
except KeyError:
    print("remove() raises KeyError")

Output

remove() raises KeyError

Version history

VersionChange
Python 3.0Added

Was this page helpful?