Python Set remove() Method
set.remove(element) deletes the element from the set in place and returns None. If the element is not in the set it raises KeyError.Use remove() when the element is supposed to be there and a missing value would be a bug, for example removing a product from a cart that you know contains it. The loud KeyError tells you your assumption was wrong.
If a missing element is perfectly normal, use set.discard(), which does the same job without the error. To take out an arbitrary element, see set.pop(). You can read more about the error itself in the KeyError lesson.
| Syntax | my_set.remove(element) |
|---|---|
| Parameters | element: the value to delete |
| Returns | None (the set is changed in place) |
| Raises | KeyError if the element is not in the set |
| Time complexity | O(1) on average |
How set.remove() works
Python looks the element up by its hash and deletes it. Equality decides a match, so remove(2) also removes the stored 2.0 if that is what the set holds, because 2 == 2.0.
stock = {"pen", "book", "ruler"}
stock.remove("book")
print(sorted(stock))Handling the KeyError from remove()
There are two clean ways to deal with a possibly missing element. Test first with in, or wrap the call in try/except. If you do not care whether it was present, discard() is shorter.
stock = {"pen", "ruler"}
if "book" in stock:
stock.remove("book")
else:
print("book is not in stock")remove() vs discard() vs pop() vs clear()
| Method | Removes | Missing element | Returns |
|---|---|---|---|
remove(x) | The element x | Raises KeyError | None |
discard(x) | The element x | Does nothing | None |
pop() | An arbitrary element | Raises KeyError if the set is empty | The removed element |
clear() | Everything | Fine on an empty set | None |
Examples you can run
Press Run, then edit the code and run it again.
Remove a sold-out item
The item exists, so remove() succeeds and the set shrinks by one.
sizes = {"S", "M", "L", "XL"}
sizes.remove("XL")
print(sorted(sizes))
print(len(sizes))Expected output['L', 'M', 'S']
3
Catch the KeyError
A realistic way to handle a missing student when un-enrolling.
enrolled = {"Asha", "Ravi"}
try:
enrolled.remove("Meera")
except KeyError:
print("Meera was not enrolled")
print(sorted(enrolled))Expected outputMeera was not enrolled
['Asha', 'Ravi']
Common mistakes
Removing something that is not there
✗ Wrong
tags = {"python", "sets"}
tags.remove("django")✓ Right
tags = {"python", "sets"}
tags.discard("django")
print(sorted(tags))Check with in first, use try/except KeyError, or call discard() if absence is fine.
Treating remove() like list.remove() on a position
✗ Wrong
nums = {10, 20, 30}
nums.remove(0)✓ Right
nums = {10, 20, 30}
nums.remove(10)
print(sorted(nums))Sets have no positions. remove() takes the value itself, not an index.
Removing while looping over the set
✗ Wrong
nums = {1, 2, 3, 4}
for n in nums:
if n % 2 == 0:
nums.remove(n)✓ Right
nums = {1, 2, 3, 4}
for n in list(nums):
if n % 2 == 0:
nums.remove(n)
print(sorted(nums))Loop over a copy such as list(nums) or build a new set with a comprehension.
Python Set remove() Method: questions people ask
What is the difference between remove() and discard() in a Python set?
remove() raises KeyError when the element is missing, while discard() silently does nothing. Both return None.
How do I remove an element from a set without an error?
Use discard(element), or check element in my_set before calling remove().
Can I remove multiple elements from a set at once?
Yes, with difference_update() or the -= operator, for example s -= {1, 2}. See set.difference() for the non-mutating version.
Keep learning
Step-by-step lessons:
Python SetsPython KeyError: What It Means and How to Fix It
Related:
Python Set discard() MethodPython Set pop() MethodPython Set clear() MethodPython Set add() Method
More in set methods:
Python Set add() MethodPython Set discard() MethodPython Set pop() MethodPython Set union() MethodPython Set intersection() MethodPython Set difference() MethodPython Set symmetric_difference() MethodPython Set update() Method See all →