pop method question

Raymond Hettinger python at rcn.com
Sun Mar 4 01:32:15 CET 2007


[Nicholas Parsons]
>  Dictionaries in Python have no order but are sequences.  
> Now, does anyone know why the python core has this pop method  
> implemented for a dictionary type?
>
> I realize that in this context it is used for removing a specific key  
> from the current dictionary object.  But why call it pop and not  
> something more intuitive like remove or delete?

The naming for pop() method followed from the naming of the previously
existing popitem() method.  Neither "remove" nor "delete" would have
been a good name for a method that looked-up and returned a value as
well as mutating the dictionary.  The word "pop" on the other hand
strongly suggests both retrieval and mutation.

The notion that "pop" is only defined for stack operations is somewhat
pedantic.  We have also successfully used the name for sets, dicts,
and deques (success meaning that most people just "get it" and are
able to learn, use, read the name without difficultly).

The rationale for the pop() method was that the pattern "v=d[k]; del
d[k]" could be collapsed to a single call, eliminating a two
successive look-ups of the same key.  Looking back, this rationale is
questionable because 1) the second lookup is not expensive because the
first lookup put the relevant hash entries in the cache, and 2) the
lookup/delete pattern for dictionaries does not seem to arise often in
practice (it does come-up every now and then in the context of set
operations).

There was also a notion that threaded programming would benefit by
having lookup-then-delete as an atomic transaction.  It is unknown to
me whether that purported benefit has ever been realized.


Raymond Hettinger




More information about the Python-list mailing list