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

Robert Kern rkern at ucsd.edu
Mon Apr 25 02:16:16 EDT 2005


Steven Bethard wrote:
> 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

Okay, okay, *almost* never.

However, I don't expect that speed relationship to hold past Python 2.4.

-- 
Robert Kern
rkern at ucsd.edu

"In the fields of hell where the grass grows high
  Are the graves of dreams allowed to die."
   -- Richard Harter




More information about the Python-list mailing list