Behaviour of pop() for dictionaries

BlindAnagram blindanagram at nowhere.org
Tue Jun 15 05:49:49 EDT 2021


On 15/06/2021 01:36, Terry Reedy wrote:
> 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).

Thanks for the interesting history.

Having found that dict.pop() caused an error, I did wonder whether it 
should have returned a (key, value) pair but quickly came to the 
conclusion that this would be awful because it would be inconsistent 
with the normal value returned by pop(x). Sadly this did not result in 
any recollection that there was a popitem() :-(

    Brian



More information about the Python-list mailing list