Set method

set.discard()

Removes an element from a set if it is there, and silently does nothing if it is not. It never raises an error.

BeginnerEvery example below runs in your browser. Change the code and press Run.

set.discard(elem)

discard(x) makes sure x is no longer in the set. If it was there, it is removed; if not, nothing happens.

Reach for it when "already gone" is a perfectly normal situation: unsubscribing someone who may never have subscribed, clearing a flag, or cleaning a set of tags.

Its twin set.remove() raises KeyError for a missing element. Choose remove() when a missing element would mean a bug you want to hear about, and discard() otherwise.

Parameters

ParameterWhat it is
elem
required
The element to remove, if present.

Return value

Nothing (None), whether or not the element was there.

Examples

1Present or not, no error

Pythoneditable
nums = {1, 2, 3}
nums.discard(2)
nums.discard(7)
print(nums)
Output
{1, 3}

2Unsubscribe from a mailing list

Pythoneditable
subscribers = {"[email protected]", "[email protected]"}
for email in ["[email protected]", "[email protected]"]:
    subscribers.discard(email)
print(sorted(subscribers))

zoe was never subscribed, and that is fine.

3Find out whether something was removed

discard() returns None either way. Compare the size if you need to know.

Pythoneditable
online = {101, 102, 103}
before = len(online)
online.discard(102)
print("removed" if len(online) < before else "was not online")
Output
removed

Common mistakes

Expecting a list to have discard()

Only sets have discard(). On a list, use if x in items: items.remove(x).

Pythoneditable
items = ["a", "b"]
if "c" in items:
    items.remove("c")
print(items)
Output
['a', 'b']

Hiding real bugs

If an element should always be present, discard() will hide the mistake when it is not. Use remove() there, so the problem shows up as an error.

Questions people ask

When should I use discard instead of remove?

Use discard() when the element may or may not be there. Use set.remove() when its absence would be an error.

How do I remove many elements without errors?

s -= other or s.difference_update(other) removes everything in other and ignores elements that are not in s.

Spotted a mistake on this page? Tell us