Content · Programming · Python

Python set.remove() vs set.discard(): Avoiding KeyError

set.remove(value) raises KeyError when the value is absent, while set.discard(value) silently does nothing. Choose whether absence should be treated as an error or as normal behavior. See two practical examples, edge.

2 views Published Oct 17, 2026 Updated Oct 18, 2026 Admin

A permissions manager revokes a permission that might already have been removed.

What You Need to Understand


set.remove(value) raises KeyError when the value is absent, while set.discard(value) silently does nothing. Choose whether absence should be treated as an error or as normal behavior.

When to Use It


A permissions manager revokes a permission that might already have been removed.

Step-by-Step Python Example


permissions = {"read", "write"}
permissions.discard("admin")
print(sorted(permissions))
try:
    permissions.remove("admin")
except KeyError:
    print("Permission was not present")

How the Example Works


The discard call succeeds without changing the set; the remove call raises the specific error that the example handles.

Example Output


['read', 'write']
Permission was not present
False

A Second Example


Compare this smaller variation with the main example, then experiment with your own values.

def delete_if_present(values, item):
    existed = item in values
    values.discard(item)
    return existed
print(delete_if_present({1, 2}, 3))

Important Behavior and Edge Cases


Avoid hiding unexpected missing values if they indicate incorrect state. discard() returns None, not a success flag.

Try It Yourself


Write a small helper that returns whether a membership was actually removed.

Common Beginner Mistakes


  • Avoid hiding unexpected missing values if they indicate incorrect state. discard() returns None, not a success flag.
  • Applying the example without a clearly defined policy for missing keys, matching identifiers, or validating external values.

Key Takeaways


  • set.remove(value) raises KeyError when the value is absent, while set.discard(value) silently does nothing.
  • The discard call succeeds without changing the set; the remove call raises the specific error that the example handles.
  • Avoid hiding unexpected missing values if they indicate incorrect state.
Share this resourceSend this page to someone who may find it useful.