<html><head></head><body style="word-wrap: break-word; -webkit-nbsp-mode: space; -webkit-line-break: after-white-space; "><br><div><div>On 9 May 2010, at 16:29, Xavier Ho wrote:</div><br class="Apple-interchange-newline"><blockquote type="cite">On Sun, May 9, 2010 at 6:20 PM, gopi krishna <span dir="ltr"><<a href="mailto:dasarathulagopi@gmail.com">dasarathulagopi@gmail.com</a>></span> wrote:<br><div class="gmail_quote"><blockquote class="gmail_quote" style="margin: 0pt 0pt 0pt 0.8ex; border-left: 1px solid rgb(204, 204, 204); padding-left: 1ex;">
Why list comprehension faster than for loop?<br><br></blockquote><div>Because Python optimises for certain special cases, when the number of iterations is predicable in a list comprehension.<br></div></div></blockquote><div><br></div><div>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.)</div><div><br></div></div></body></html>