An application attempts to revoke an optional permission without failing if it was already gone.
What You Need to Understand
set.discard(element) removes one member if present; unlike remove(), it does nothing if the value is absent. It always returns None.
When to Use It
An application attempts to revoke an optional permission without failing if it was already gone.
Step-by-Step Python Example
permissions = {"read", "write"}
permissions.discard("write")
permissions.discard("admin")
print(sorted(permissions))
How the Example Works
The write permission disappears; discarding the missing admin permission is harmless.
Example Output
['read']
None
A Second Example
Compare this smaller variation with the main example, then experiment with your own values.
items = set()
print(items.discard("unknown"))
Important Behavior and Edge Cases
Use remove() when absence indicates a real bug and should raise KeyError; use discard() when absence is expected.
Try It Yourself
Discard a member from an empty set and inspect the result.
Common Beginner Mistakes
- Use
remove()when absence indicates a real bug and should raiseKeyError; usediscard()when absence is expected. - Using the wrong collection method for this operation without checking whether it mutates the object, returns a result, or raises on missing data.
Key Takeaways
set.discard(element)removes one member if present; unlikeremove(), it does nothing if the value is absent.- The write permission disappears; discarding the missing admin permission is harmless.
- Use
remove()when absence indicates a real bug and should raiseKeyError; usediscard()when absence is expected.