[Newby question] List comprehension
peter at engcorp.com
Fri Aug 6 17:37:07 CEST 2004
Hallvard B Furuseth wrote:
> Eelco Hoekema wrote:
>>Batista, Facundo schreef:
>>>Now, explain me why a list comprehension is better here.
>>Are they better? Don't know. In Dive into Python, Mark Pilgrim states
>>compared to list comprehensions, for loops are a waste of time. Not
>>sure what he means by that, though.
> List comprehensions are faster.
Time for the old refrain "Premature optimization is the root of
all evil in programming." (Knuth)
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.
More information about the Python-list