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

Robert Kern rkern at ucsd.edu
Mon Apr 25 06:17:19 EDT 2005


jfj 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?
> 
> If you want a list right away you'd use a list comprehension.
>  X =[i for i in something() if somethingelse()]
>  random.shuffle(X)
>  print x[23]
> 
> On the other hand it's generator expressions which should be used
> only when the code can be written in as a pipe.  For example a filter
> of a -otherwise- very long list:
> 
>   make_fractal_with_seed (x for x in range(100000000) if fibonacci_prime 
> (x))
> 
>> Never. If you really need a list
>>
>> list(x*x for x in xrange(10))
>>
>> Sadly, we can't remove list comprehensions until 3.0.
>>
> 
> Why???
> Then we should also remove:
>  x=[] to x=list()
>  x=[1,2,3] to x=list(1,2,3)

Well, that last one doesn't work. Removing the empty list literal would 
be inconsistent.

> I think "list" is useful only:
> 1) to subclass it
> 2) to convert a list/tuple/string to a list, which is
> done extremely fast.

Add "any iteratable". Genexps are iterables.

> But for iterators I find the list comprehension syntax nicer.

Possibly. I find them too similar with little enough to choose between 
them, hence the OP's question.

-- 
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