The set.remove() method deletes a specified element from a set in-place and returns None. If the element is not found, Python raises a KeyError.
Alternative Method: When you want to remove an item without throwing an exception if it is missing, use set.discard() instead.
The remove() method is invoked directly on a set instance:
set_name.remove(element)
| Parameter | Type | Required? | Description |
|---|---|---|---|
element |
Hashable (int, str, tuple, etc.) |
Yes | The specific item to delete from the set. Must be a hashable object. |
Return Value: Returns None. The set is mutated directly in-place.
Passing an existing member to remove() deletes that element and updates the set in memory:
technologies = {"Python", "SQL", "Pandas", "Docker"}
print("Before:", technologies)
# Delete "Docker"
return_val = technologies.remove("Docker")
print("After: ", technologies)
print("Return value:", return_val) # Always None
Before: {'Python', 'Pandas', 'SQL', 'Docker'}
After: {'Python', 'Pandas', 'SQL'}
Return value: None
If you attempt to remove an item that does not exist in the set, Python raises a KeyError:
languages = {"English", "Spanish", "German"}
# Attempting to delete an item that isn't present
languages.remove("French")
# Output: KeyError: 'French'
To safely handle missing items, use one of the following two idiomatic patterns:
try...except KeyError Blocktry:
languages.remove("French")
except KeyError:
print("Notice: 'French' was not in the set.")
intarget = "French"
if target in languages:
languages.remove(target)
Python provides several distinct methods for removing items from a set. Choosing the right one depends on how missing elements and return values should be treated:
| Method | Element Exists | Element Missing | Return Value | Primary Use Case |
|---|---|---|---|---|
set.remove(x) |
Removes x |
Raises KeyError |
None |
When the element's absence indicates a logical error or unexpected program state. |
set.discard(x) |
Removes x |
Silently ignores (no error) | None |
When the element is optional and its absence is completely safe to ignore. |
set.pop() |
Removes an arbitrary element | Raises KeyError (empty set) |
The removed element | Consuming tasks or elements from a pool where order does not matter. |
set.clear() |
Empties entire set | No error (already empty) | None |
Resetting a set to zero elements while preserving its memory reference. |
Attempting to remove items from a set while looping directly over it will raise a RuntimeError: Set changed size during iteration:
scores = {45, 88, 92, 56, 73}
# BUG: Changing set size while iterating directly
for s in scores:
if s < 60:
scores.remove(s) # Raises RuntimeError!
To safely remove multiple items based on a condition, use one of these two proven techniques:
scores = {45, 88, 92, 56, 73}
for s in list(scores): # Snapshot the elements into a list
if s < 60:
scores.remove(s)
print("Passing Scores:", scores) # Output: {73, 88, 92}
scores = {45, 88, 92, 56, 73}
failing_scores = {s for s in scores if s < 60}
scores.difference_update(failing_scores)
print("Passing Scores:", scores)
Python sets are implemented as hash tables. Because element positions are computed directly from their hash values, set.remove() has an average time complexity of Ο(1) (constant time):
list or dict) raises a TypeError: unhashable type: 'list'.Let's build a real-time web server session tracker that tracks active user IDs, safely logging out sessions using remove() and handling KeyError:
class SessionTracker:
def __init__(self):
self.active_sessions = set()
def login(self, user_id):
self.active_sessions.add(user_id)
def logout(self, user_id):
try:
self.active_sessions.remove(user_id)
return True # Successfully logged out
except KeyError:
return False # Was not logged in
def is_online(self, user_id):
return user_id in self.active_sessions
# Execute tracker workflow
tracker = SessionTracker()
tracker.login("user_alpha")
tracker.login("user_beta")
# Self-checking unit assertions
assert tracker.is_online("user_alpha") is True
assert tracker.is_online("user_beta") is True
assert tracker.is_online("user_gamma") is False
# Successful logout
logout_alpha = tracker.logout("user_alpha")
assert logout_alpha is True
assert tracker.is_online("user_alpha") is False
# Redundant logout (verifies KeyError is caught and handled)
logout_alpha_repeat = tracker.logout("user_alpha")
assert logout_alpha_repeat is False
print("Remaining Active Sessions:", tracker.active_sessions)
print("All SessionTracker assertions passed successfully!")
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.