What's do list comprehensions do that generator expressions don't?

Steven Bethard steven.bethard at gmail.com
Mon Apr 25 02:04:12 EDT 2005


Robert Kern wrote:
> Mike Meyer wrote:
> 
>> Ok, we've added list comprehensions to the language, and seen that
>> they were good. We've added generator expressions to the language, and
>> seen that they were good as well.
>>
>> I'm left a bit confused, though - when would I use a list comp instead
>> of a generator expression if I'm going to require 2.4 anyway?
> 
> Never. If you really need a list
> 
> list(x*x for x in xrange(10))

Not quite true.  If you discovered the unlikely scenario that the 
construction of a list from the generator expression was an efficiency 
bottleneck, you might choose a list comprehension -- they're slightly 
faster when you really do want a list:

$ python -m timeit "list(x*x for x in xrange(10))"
100000 loops, best of 3: 6.54 usec per loop

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

STeVe



More information about the Python-list mailing list