ReferenceSet methods

Python Set remove() Method

Short answer
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.

Quick facts
Syntaxmy_set.remove(element)
Parameterselement: the value to delete
ReturnsNone (the set is changed in place)
RaisesKeyError if the element is not in the set
Time complexityO(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.

Python
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.

Python
stock = {"pen", "ruler"}
if "book" in stock:
    stock.remove("book")
else:
    print("book is not in stock")

remove() vs discard() vs pop() vs clear()

MethodRemovesMissing elementReturns
remove(x)The element xRaises KeyErrorNone
discard(x)The element xDoes nothingNone
pop()An arbitrary elementRaises KeyError if the set is emptyThe removed element
clear()EverythingFine on an empty setNone

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.

Remove a sold-out item
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.

Catch the KeyError
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")
KeyError: '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)
KeyError: 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)
RuntimeError: Set changed size during iteration

✓ 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 →