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

jfj jfj at freemail.gr
Mon Apr 25 05:18:20 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?

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)

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.

But for iterators I find the list comprehension syntax nicer.


jfj




More information about the Python-list mailing list