Idiosyncratic python

Steven D'Aprano steve+comp.lang.python at pearwood.info
Thu Sep 24 02:35:27 EDT 2015


On Thursday 24 September 2015 16:16, Paul Rubin wrote:

> Steven D'Aprano <steve+comp.lang.python at pearwood.info> writes:
>> for k, v in mydict.items():
>>     del(k)
> 
> That looks wrong: it's deleting k from what?

The local namespace.

py> k = 23
py> print k
23
py> del k
py> print k
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'k' is not defined

 
>> instead of the more obvious
>> for v in mydict.values():
>>     ...
> 
> Maybe you mean
> 
>    while mydict:
>       k, v = mydict.popitem()
>       ...


Hah, no, you're the second person to make that mistake! One of the guys I 
work with suggested `mydict = {}` to empty the dict.

`del k` (aside: no need for parens, del is a statement, not a function) 
doesn't delete the key from the dictionary. It just deletes the name k. The 
obvious intent is to iterate over the *values* of the dictionary, but the 
coder didn't know about values, so he iterated over (key,value) pairs, then 
deleted the key local variable (not the key in the dict!) to keep the 
namespace clean.



-- 
Steve




More information about the Python-list mailing list