discard(item) removes item from a set if it is there. If it is not there, nothing happens: no error, no change. The set is changed in place.
That is the difference from remove(), which raises KeyError for a missing item. Choose discard() when you only care that the item is gone afterwards, not that it was there before.
set.discard() is an instance method of the built-in set type: call it on a set with dot notation, such as guests.discard(...). No import is needed.
Syntax
Pass the item to delete, and call it on its own line, because the return value is always None.
python
s.discard(item)
Call
What it does
{1, 2, 3}.discard(2)
Returns None; the set becomes {1, 3}.
{1, 2, 3}.discard(9)
Returns None; the set becomes {1, 2, 3}, unchanged: a missing item is not an error.
{"a"}.discard(["a"])
Raises TypeError: a list cannot be looked up in a set because it is unhashable.
discard() never tells you whether it removed anything. If you need to know, compare len(s) before and after, or test item in s first.
Method signatures
python
set.discard(item)
# returns: None; item is no longer in the set
# raises: TypeError if item is unhashable (never KeyError)
Parameters
Parameter
Description
item
The value to delete, matched by equality. It must be hashable, so a list raises TypeError. It is required: discard() with no argument raises TypeError as well.
Return Value
Return Value
Description
None
Always None, whether the item was removed or not.
Python Examples
Example 1 — Cancel RSVPs Without Errors
Discard a list of names, some of which never signed up.
python
rsvp = {"Mia", "Noah", "Zoe", "Liam"}
for name in ["Noah", "Ava", "Zoe"]:
rsvp.discard(name)
print(sorted(rsvp))
print(len(rsvp))
Output
['Liam', 'Mia']
2
How It Works
Known names are removed. Noah and Zoe were in the set, so both are deleted.
Unknown names are ignored. Ava never signed up, so discarding her changes nothing and raises nothing.
Two guests remain. Mia and Liam are left, and sorted() prints them alphabetically.
Example 2 — Compare discard() With remove()
Delete a code that does not exist with both methods and watch which one complains.