How complex is complex?

Casey Webster Caseyweb at gmail.com
Wed Mar 18 14:03:06 EDT 2009


On Mar 18, 1:30 pm, Kottiyath <n.kottiy... at gmail.com> wrote:
> When we say readability counts over complexity, how do we define what
> level of complexity is ok?
> For example:
> Say I have dict a = {'a': 2, 'c': 4, 'b': 3}
> I want to increment the values by 1 for all keys in the dictionary.
> So, should we do:>>> for key in a:
>
> ...   a[key] = a[key] + 1
> or is it Ok to have code like:
> dict(map(lambda key: (key, a[key] + 1), a))
>
> How do we decide whether a level of complexity is Ok or not?

This isn't just a question of readability; the two expressions are
entirely different. The second expression creates a whole new
dictionary, which might not have been obvious to you given the overall
complexity of the expression. The first expression is simple, clear,
and other than maybe changing "a[key] = a[key] + 1" to "a[key] += 1"
is pretty much hard to improve on.  If the number of lines matters to
you (it shouldn't, be opinions vary), then you could always write:

>>> for k in a: a[k] += 1

Which is shorter and far easier to read than the dict/map/lambda
expression.  And probably what you really intended!



More information about the Python-list mailing list