How complex is complex?

bearophileHUGS at lycos.com bearophileHUGS at lycos.com
Wed Mar 18 14:02:03 EDT 2009


Kottiyath:
> How do we decide whether a level of complexity is Ok or not?

I don't understand your question, but here are better ways to do what
you do:

>>> a = {'a': 2, 'c': 4, 'b': 3}
>>> for k, v in a.iteritems():
...   a[k] = v + 1
...
>>> a
{'a': 3, 'c': 5, 'b': 4}
>>> b = dict((k, v+1) for k, v in a.iteritems())
>>> b
{'a': 4, 'c': 6, 'b': 5}

The first modifies the dict in-place, and the second created a new
dict.

In Python 3 those lines become shorter:

for k, v in a.items():
{k: v+1 for k, v in a.items()}

Bye,
bearophile



More information about the Python-list mailing list