Guide Python Beginner

12.5 Removing Elements

remove() vs discard() -- the same removal, but one raises KeyError on a missing value and the other doesn't -- plus pop()'s arbitrary-element removal, clear(), and why del can only delete the whole set variable.

2 min read

remove()

Removes a specific value — raises KeyError if it isn’t present.

>>> s = {1, 2, 3}
>>> s.remove(2)
>>> s
{1, 3}
>>> s.remove(99)
Traceback (most recent call last):
KeyError: 99

discard()

Same as remove(), but does not raise an error if the value is absent — the safer choice when it’s not certain the item exists.

>>> s.discard(99)      # no error, even though 99 isn't in the set
>>> s
{1, 3}

pop()

Removes and returns an arbitrary element — since sets are unordered (see 12.6 Set Indexing and Ordering), there’s no “first” or “last” to remove, unlike list.pop().

>>> p = s.pop()
>>> type(p)
<class 'int'>

clear()

>>> s2 = {1, 2, 3}
>>> s2.clear()
>>> s2
set()

del Statement

del doesn’t remove individual set elements (sets aren’t indexed) — it can only delete the entire set variable, same as for any other type.

>>> s3 = {1, 2, 3}
>>> del s3
>>> s3
Traceback (most recent call last):
NameError: name 's3' is not defined

Quick Interview Answer

“remove() and discard() do the identical removal — the only difference is that remove() raises KeyError if the value isn’t present, and discard() silently does nothing. That makes discard() the safer default whenever it isn’t already known the value exists. pop() is different from a list’s pop(): since a set has no order, there’s no ’last element’ to remove — it takes and returns an arbitrary one instead. And del never targets a set element the way it can a list index; it can only remove the variable binding itself, since sets aren’t indexed.”

Common Mistakes

  • Using remove() on a value that might not exist and getting an unhandled KeyError — use discard(), or check membership with in first.
  • Expecting pop() to remove a specific or “last-added” element — it removes whichever element the hash table happens to yield first, which is not predictable.
  • Trying del s[0] to remove an element — sets aren’t subscriptable at all (see 12.6 Set Indexing and Ordering); del only works on the variable name.

Add More Questions to This Guide

Know a question that should be here? Share it and help the community!

Open Google Form