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.
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
| Parameter | What it is |
|---|---|
elemrequired | The element to remove, if present. |
Return value
Nothing (None), whether or not the element was there.
Examples
1Present or not, no error
nums = {1, 2, 3}
nums.discard(2)
nums.discard(7)
print(nums){1, 3}2Unsubscribe from a mailing list
subscribers = {"ana@mail.com", "ben@mail.com"}
for email in ["ben@mail.com", "zoe@mail.com"]:
subscribers.discard(email)
print(sorted(subscribers))['ana@mail.com']
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.
online = {101, 102, 103}
before = len(online)
online.discard(102)
print("removed" if len(online) < before else "was not online")removed
Common mistakes
Expecting a list to have discard()
Only sets have discard(). On a list, use if x in items: items.remove(x).
items = ["a", "b"]
if "c" in items:
items.remove("c")
print(items)['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.