Behaviour of pop() for dictionaries
Terry Reedy
tjreedy at udel.edu
Mon Jun 14 20:36:49 EDT 2021
On 6/14/2021 5:18 PM, BlindAnagram wrote:
> I believe that consistency in how methods common to different types work
> is useful since it adds to the coherence of the language as a whole and
> avoids the need to remember special cases.
Each collection class *is* a special case, and pop has to be adjusted to
each. However, you seem to have missed an essential commonality.
Lists and dicts are both subscripted classes. So the basic API is
col.pop(sub), which removes and returns the sub item, whereas col[sub]
leaves and returns.
Lists have a special index, -1, the most commonly used, so that is the
default. In fact, when I proposed list.pop(), I only proposed that, as
I wanted pop to be the inverse of append, so a list could be used as a
stack.
Bad list subscripts are an error (unless one is slicing), whereas where
dicts allow a default (when subscripted with the get method). Hence the
optional default only for dicts.
At one time, dicts, like sets, were unordered collections (of functional
item pairs). dict.pop(), with no arg, could have been used to return a
random 2-ple, but Guido is generally against having return types depend
on arguments. So a new popxxx name was added. Note that deques have a
popleft in addition to pop (right).
--
Terry Jan Reedy
More information about the Python-list
mailing list