Pythonic way to sum n-th list element?

Alex Martelli aleax at aleax.it
Sat Apr 19 04:05:49 EDT 2003


Tyler Eaves wrote:
   ...
> Wow, I feel vindicated now for never trying to wrap my brain around stuff
> like list comprehensions. *g*

And here, you're wrong - list comprehensions are VERY worth "wrapping
your brain around"!  They allow clear and direct expression and their
performance is generally quite OK.

E.g. "make a list L of N*N+1 for N in range(1000)":

[alex at lancelot python2.3]$ python2.2 -O timeit.py 'L=[]' 'for i in 
range(1000):' '  L.append(i*i+1)'
1000 loops, best of 3: 1.45e+03 usec per loop

[alex at lancelot python2.3]$ python2.2 -O timeit.py 'L = map(lambda i: i*i+1, 
range(1000))'
1000 loops, best of 3: 1.23e+03 usec per loop

[alex at lancelot python2.3]$ python2.2 -O timeit.py 'L = [i*i+1 for i in 
range(1000)]'
1000 loops, best of 3: 1.1e+03 usec per loop

the LC form expresses the specs directly and even has a little performance
advantage in this case over the map/lambda form and the direct loop.  Study
up on list comprehensions, you'll be glad you did!


Alex





More information about the Python-list mailing list