Popping key causes dict derived from object to revert to object

Grant Edwards grant.b.edwards at gmail.com
Mon Mar 25 11:54:59 EDT 2024


On 2024-03-25, Loris Bennett via Python-list <python-list at python.org> wrote:
> Grant Edwards <grant.b.edwards at gmail.com> writes:
>
>> On 2024-03-22, Loris Bennett via Python-list <python-list at python.org> wrote:
>>
>>> Yes, I was mistakenly thinking that the popping the element would
>>> leave me with the dict minus the popped key-value pair.
>>
>> It does.
>
> Indeed, but I was thinking in the context of 
>
>   dict_list = [d.pop('a') for d in dict_list]
>
> and incorrectly expecting to get a list of 'd' without key 'a', instead
> of a list of the 'd['a]'.

So when you say "leave me with", you mean "return the same dictionary
with"?  There's an important difference between what a function
returns and what global/local state it "leaves you with".

> Thanks for pointing out 'del'.  My main problem, however, was
> failing to realise that the list comprehension is populated by the
> return value of the 'pop', not the popped dict.

OK, so perhaps you weren't execting the original dict objects to be
mutated, but rather that the pop method would return a new dict object
without the "popped" element. The whole point of the 'pop method is to
return the popped value, otherwise it wouldn't be needed. The 'del'
statement would suffice.



More information about the Python-list mailing list