[Newby question] List comprehension
peter at engcorp.com
Fri Aug 6 12:50:19 EDT 2004
Eelco Hoekema wrote:
> Peter Hansen schreef:
>>List comprehensions may be faster, but that is never a valid reason,
>>in isolation, for choosing one construct over another.
>>If (a) list comprehensions can't do this, or (b) one has to jump
>>through hoops and make the construct completely unreadable to make
>>it work, then list comprehensions are completely unsuited to the
>>task at hand.
>>A loop, on the other hand, works just fine and is very readable.
>>Use a loop.
> I'm a bit puzzled. Are you saying one should never use a list
> comprehension? Or are you just referring to this specific problem, where i
> would have to cheat in order to get the things done in one single list
Definitely referring only to cases such as this one, where you
have to "cheat". The fact that it's not straightforward to do
should immediately lead someone in the direction of finding the
more obvious and simple approach. In this case, that's a loop.
(Someone may well find an elegant way to do it with a nice
concise list comprehension. Such a way may well become an
accepted idiom at some point in the future. Neither of these
points has any bearing on the fact that most of us shouldn't
spend time trying to shoehorn overly complicated structures into
constructs that can't easily handle them.)
I do use list comprehensions myself. Never (yet) for reasons
of performance, and never for complicated ones because I always
find the loop variant to be more readable once they've grown
beyond the relatively simple ones like this:
[(foo, bar(foo)) for foo in someList if foo is not a baz]
More information about the Python-list