FAQ
Why list comprehension faster than for loop?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20100509/b4498631/attachment.html>

Search Discussions

  • Xavier Ho at May 9, 2010 at 8:29 am

    On Sun, May 9, 2010 at 6:20 PM, gopi krishna 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.

    Cheers,
    Xav
    -------------- next part --------------
    An HTML attachment was scrubbed...
    URL: <http://mail.python.org/pipermail/python-list/attachments/20100509/39f68428/attachment-0001.html>
  • Trent Nelson at May 9, 2010 at 11:02 am
    On 9 May 2010, at 16:29, Xavier Ho wrote:

    On Sun, May 9, 2010 at 6:20 PM, gopi krishna <dasarathulagopi at gmail.comwrote:
    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.html>

Related Discussions

Discussion Navigation
viewthread | post
Discussion Overview
grouppython-list @
categoriespython
postedMay 9, '10 at 8:20a
activeMay 9, '10 at 11:02a
posts3
users3
websitepython.org

People

Translate

site design / logo © 2022 Grokbase