Python Set discard() Method
set.discard(element) removes the element from the set if it is present and does nothing if it is not. It always returns None and never raises KeyError.discard() is the forgiving cousin of remove(). It is ideal when you want a value to be gone afterwards but do not care whether it was there before, such as unsubscribing an email address that might already have been removed.
Because there is no error to catch, the code stays short. Use remove() instead when a missing element signals a real problem you want to hear about.
| Syntax | my_set.discard(element) |
|---|---|
| Parameters | element: the value to remove if present |
| Returns | None (the set is changed in place) |
| Raises | Nothing for a missing element; TypeError for an unhashable one |
| Time complexity | O(1) on average |
How set.discard() works
Python looks up the element by hash. If found, it is deleted. If not, the call ends quietly.
users = {"asha", "ravi"}
users.discard("ravi")
users.discard("meera") # not present, no error
print(sorted(users))When to choose discard() over remove()
Pick discard() for cleanup steps and idempotent operations: running it twice should leave the same result as running it once. Pick remove() when a missing item indicates corrupted data and you want the program to stop. Both are O(1) on average. If you need the removed value back, use pop().
| Situation | Better method |
|---|---|
| Unsubscribe an address that may be gone | discard() |
| Remove a cart item that must exist | remove() |
| Clear tags that may not be set | discard() |
| Take any element and process it | pop() |
| Empty the whole set | clear() |
Examples you can run
Press Run, then edit the code and run it again.
Safe unsubscribe
Calling discard() twice is harmless, so the second call needs no special handling.
subscribers = {"a@x.com", "b@x.com", "c@x.com"}
subscribers.discard("b@x.com")
subscribers.discard("b@x.com")
print(sorted(subscribers))Expected output['a@x.com', 'c@x.com']
Discard several unwanted values in a loop
Loop over a list of blocked words; missing ones are simply skipped.
words = {"spam", "hello", "offer", "python"}
for bad in ["spam", "offer", "virus"]:
words.discard(bad)
print(sorted(words))Expected output['hello', 'python']
Common mistakes
Expecting discard() to return the element
✗ Wrong
s = {1, 2, 3}
removed = s.discard(2)
print(removed)✓ Right
s = {1, 2, 3}
was_there = 2 in s
s.discard(2)
print(was_there, sorted(s))discard() returns None whether or not it removed something. Use pop() if you need a value back, or test with in first.
Discarding an unhashable value
✗ Wrong
s = {1, 2}
s.discard([1, 2])✓ Right
s = {(1, 2), (3, 4)}
s.discard((1, 2))
print(s)Pass a hashable value. Convert a list to a tuple if your set stores tuples.
Python Set discard() Method: questions people ask
Does set.discard() raise an error if the element is not found?
No. It does nothing when the element is absent, which is exactly how it differs from remove().
What does discard() return in Python?
It returns None every time, whether or not an element was removed.
Is discard() faster than remove()?
They have the same O(1) average cost. Choose by whether a missing element should be an error, not by speed.
Keep learning
Step-by-step lessons:
Python SetsPython Set Operations
Related:
Python Set remove() MethodPython Set pop() MethodPython Set clear() MethodPython Set add() Method
More in set methods:
Python Set add() MethodPython Set remove() MethodPython Set pop() MethodPython Set union() MethodPython Set intersection() MethodPython Set difference() MethodPython Set symmetric_difference() MethodPython Set update() Method See all →