How complex is complex?
Terry Reedy
tjreedy at udel.edu
Fri Mar 20 15:49:24 EDT 2009
Vito De Tullio wrote:
> Tim Roberts wrote:
>
>> bearophileHUGS at lycos.com wrote:
>>> In Python 3 those lines become shorter:
>>>
>>> for k, v in a.items():
>>> {k: v+1 for k, v in a.items()}
This is nonsensical. It creates and discards a complete new dict for
each item in the original dict. The reuse of names 'k' and 'v' in the
comprehension just confuse.
>> That's a syntax I have not seen in the 2-to-3 difference docs, so I'm not
>> familiar with it. How does that cause "a" to be updated?
It does not.
> I think he would write
>
>>>> a = { 'a': 4, 'c': 6, 'b': 5 }
>>>> a = { k:v+1 for k, v in a.items() }
>>>> a
> {'a': 5, 'c': 7, 'b': 6}
This *replaces* original dict a with a new dict rather than updating
(its values) in place. This is less efficient. If there are other
references to the original dict, the rebinding may or may not be correct.
I believe the in-place update was already given as:
for k,v in a.items(): a[k] = v+1 # or
for k in a.keys(): a[k] += 1
Terry Jan Reedy
More information about the Python-list
mailing list