List comprehensions performance

Bengt Richter bokr at oz.net
Thu Sep 30 19:45:38 CEST 2004


On Thu, 30 Sep 2004 10:55:52 +0200, aleaxit at yahoo.com (Alex Martelli) wrote:

>Raymond Hettinger <vze4rx4y at verizon.net> wrote:
>
>> [Neuruss] What I'd like to know is if using list comprehensions would give
>> me a > performance advantage over traditional for loops or not.
>> 
>> For Py2.4, list comprehensions are much faster than equivalent for-loops.
>
>...but if the for loop is NOT equivalent (it doesn't accumulate results
>into a resulting list), it's still faster.  As I posted:
>
>kallisti:~/cb alex$ python2.4 timeit.py -s'def f():pass' 'for x in
>xrange(999): f()'
>1000 loops, best of 3: 1.29e+03 usec per loop
>kallisti:~/cb alex$ python2.4 timeit.py -s'def f():pass' '[f() for x in
>xrange(999)]'
>1000 loops, best of 3: 1.45e+03 usec per loop
>
>the LC is paying for the building of a list of 999 references to None,
>which the for loop easily avoids, so the for loop is much faster here.
>

What if you abuse the LC so it makes an empty list? E.g.,
    [None for x in xrange(999) if f() and False]

Not that I'm trying to promote LC abuse ;-)

Regards,
Bengt Richter



More information about the Python-list mailing list