Why list comprehension faster than for loop?
Trent Nelson
trent at snakebite.org
Sun May 9 07:02:28 EDT 2010
On 9 May 2010, at 16:29, Xavier Ho wrote:
On Sun, May 9, 2010 at 6:20 PM, gopi krishna <dasarathulagopi at gmail.com<mailto:dasarathulagopi at gmail.com>> wrote:
Why list comprehension faster than for loop?
Because Python optimises for certain special cases, when the number of iterations is predicable in a list comprehension.
The fact that list comprehensions can only be comprised of expressions, not statements, is a considerable factor, as much less work is required behind the scenes for each iteration. Another factor is that the underlying iteration mechanism for list comprehensions is much closer to a C loop than execution of a for loop. Exact same reason Perl's map { } is much faster than an equivalent for/foreach loop. (Psyco can speed up certain list comprehensions quite significantly, too, but it isn't able to perform the same magic on an equivalent for loop.)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20100509/e4bd6859/attachment-0001.html>
More information about the Python-list
mailing list