5

Why do empty sets and lists raise different exceptions when you call .pop()?

>>> l = []
>>> l.pop()
Traceback (most recent call last):
  File "<pyshell#15>", line 1, in <module>
    l.pop()
IndexError: pop from empty list
>>> l = set()
>>> l.pop()
Traceback (most recent call last):
  File "<pyshell#17>", line 1, in <module>
    l.pop()
KeyError: 'pop from an empty set'
Joschua
  • 5,816
  • 5
  • 33
  • 44

2 Answers2

7

Because sets are a lot like dicts but without the values:

>>> d = {}
>>> d.pop('foo')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'pop(): dictionary is empty'

Both dictionaries and sets are not indexed, like lists are, so an IndexError makes no sense here. But like dictionaries, there is only ever one value of each 'key' in the set.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Getting a `KeyError` when the key provided to `dict.pop({key value})` doesn't exist, regardless of whether or not the dictionary is empty, certainly makes sense, but not so much with `set.pop()` which does not accept one as an argument. My guess is that it's to be compatible with the `Set` class in the [`sets`](http://docs.python.org/2/library/sets.html) module introduced in Python 2.3 which were implemented using dictionaries according to the documentation. – martineau Mar 03 '13 at 22:25
  • @martineau: `.remove()` also raises a `KeyError`. According to [this commit](http://hg.python.org/cpython/file/3086620db46b/Objects/setobject.c) it was modeled after `dict.pop()` *explicitly*. – Martijn Pieters Mar 03 '13 at 22:31
  • `Set.remove()` in the `sets` module did this so it likely just backwards compatibility again, _and_ like `dict.pop()` -- but unlike both `Set.pop()` and `set.pop()` -- the `set.remove()` method also takes an argument (although it's called _elem_ in the documentation, not _key_). All of which make me doubt that the commit comment could be considered strong evidence. – martineau Mar 03 '13 at 22:59
7

Lists are ordered sequences, accessed by index; sets are unordered and non-sequential, accessed by key, hence the error messages.

Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561