set.discard()
set.discard(elem) None · Updated March 15, 2026 · Set Methods The .discard() method removes an element from a set if it is present. Unlike .remove(), it does not raise a KeyError if the element doesn’t exist — the operation simply does nothing. This makes .discard() safer for cases where you’re uncertain whether the element is in the set.
Syntax
set.discard(elem)
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
elem | any | — | The element to remove from the set. If not present, nothing happens. |
Examples
Basic usage
Remove an element that exists:
fruits = {"apple", "banana", "cherry"}
fruits.discard("banana")
print(fruits)
# {'apple', 'cherry'}
Discarding a non-existent element
Unlike .remove(), .discard() silently does nothing if the element isn’t there:
numbers = {1, 2, 3}
numbers.discard(99) # No error, even though 99 is not in the set
print(numbers)
# {1, 2, 3}
This behavior is useful when you want to remove something without checking if it exists first.
Comparing discard() vs remove()
The key difference becomes clear when the element doesn’t exist:
my_set = {1, 2, 3}
# Using remove() - raises KeyError
try:
my_set.remove(99)
except KeyError:
print("remove() raised KeyError")
# remove() raised KeyError
# Using discard() - silent success
my_set.discard(99) # No error
print("discard() succeeded silently")
# discard() succeeded silently
Safe removal pattern
Use .discard() when you’re not sure if an element is present:
user_permissions = {"read", "write"}
# User loses "delete" permission if they had it, nothing happens if they didn't
user_permissions.discard("delete")
print(user_permissions)
# {'read', 'write'}
Conditional removal in loops
When processing items that may or may not be in a set:
available_toppings = {"cheese", "pepperoni", "mushrooms", "olives"}
ordered_toppings = ["cheese", "pineapple", "mushrooms", "extra cheese"]
for topping in ordered_toppings:
available_toppings.discard(topping)
print(f"Added: {topping}")
print(f"Remaining: {available_toppings}")
# Added: cheese
# Added: pineapple
# Added: mushrooms
# Added: extra cheese
# Remaining: {'pepperoni', 'olives'}
Notice that pineapple and extra cheese weren’t in the original set, but no error was raised.
Cleaning up related items
Remove multiple related items safely:
tags = {"python", "coding", "programming", "tutorial", "guide"}
# Remove all related tags at once without checking
tags.discard("tutorial")
tags.discard("guide")
print(tags)
# {'python', 'coding', 'programming'}
Common Patterns
Set difference operation
Simulate set difference with .discard():
def remove_items(target_set, items_to_remove):
for item in items_to_remove:
target_set.discard(item)
return target_set
numbers = {1, 2, 3, 4, 5}
remove_items(numbers, [3, 5, 7])
print(numbers)
# {1, 2, 4}
Filtering unique items
Remove items from a set based on a condition:
valid_codes = {"A100", "B200", "C300", "D400"}
submitted_codes = ["A100", "X999", "B200", "Y888"]
for code in submitted_codes:
valid_codes.discard(code)
print(valid_codes)
# {'C300', 'D400'}
Safe cleanup in error handling
Useful in cleanup code where you’re not sure what state the set is in:
def cleanup_session(session_data):
# Clean up various items regardless of whether they exist
session_data.active_users.discard(current_user_id)
session_data.open_connections.discard(connection_id)
session_data.cached_data.discard(cache_key)
# No need for try/except blocks
Performance
The .discard() method has:
- Average case: O(1) time complexity
- Worst case: O(n) when hash collisions occur
The performance is essentially the same as .remove() — the only difference is the error behavior.
See Also
- set::set.add() — adds an element to a set
- set::set.clear() — removes all elements from the set
- set::set.difference_update() — removes multiple elements at once