shouldn't list comprehension be faster than for loops?
Gregory Ewing
greg.ewing at canterbury.ac.nz
Sat Dec 19 00:49:24 EST 2009
Ryan Kelly wrote:
>Someone else wrote:
>>It will be the
>>same as the difference between a for loop and a call to map.
>
> Not so. If you use the "dis" module to peek at the bytecode generated
> for a list comprehension, you'll see it's very similar to that generated
> for an explicit for-loop.
The usual advice is that if you have a built-in function that
does what you want done for each element, then using map() is
probably the fastest way.
However, if you need to create a Python function to pass to
map(), the list comprehension may well be faster, because it
avoids the cost of a Python function call per element.
--
Greg
More information about the Python-list
mailing list