removing list comprehensions in Python 3.0

Steven Bethard steven.bethard at gmail.com
Fri Jul 8 20:32:04 EDT 2005


Devan L wrote:
> List comprehensions are faster than generator comprehensions for
> iterating over smaller sequences.

Could you give me an example?  For the simple one below, the generator 
expression was faster:

$ python -m timeit "for x in (i for i in xrange(10)): y = x"
100000 loops, best of 3: 4.75 usec per loop

$ python -m timeit "for x in [i for i in xrange(10)]: y = x"
100000 loops, best of 3: 5.33 usec per loop


And for another one, the results are basically indistinguishable:

$ python -m timeit "for x in (i for i in 'abcdefg'): y = x"
100000 loops, best of 3: 3.82 usec per loop

$ python -m timeit "for x in [i for i in 'abcdefg']: y = x"
100000 loops, best of 3: 3.87 usec per loop


I vaguely remember that in Python 2.4 conversion to tuples can take 
longer because of the tuple extension code:

$ python -m timeit "tuple(i for i in xrange(10000))"
100 loops, best of 3: 2.24 msec per loop

$ python -m timeit "tuple([i for i in xrange(10000)])"
100 loops, best of 3: 1.85 msec per loop

But IIRC, this is supposed to be fixed in Python 2.5.


I found that for some longer sequences, generator expressions were 
notably faster:

$ python -m timeit "set(i for i in xrange(10000))"
100 loops, best of 3: 3.77 msec per loop

$ python -m timeit "set([i for i in xrange(10000)])"
100 loops, best of 3: 4.54 msec per loop


Timings that validate your statement would be appreciated. ;)

STeVe



More information about the Python-list mailing list