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

Mike Meyer mwm at mired.org
Tue Apr 26 03:12:07 EDT 2005


bokr at oz.net (Bengt Richter) writes:

> On Mon, 25 Apr 2005 16:48:46 -0400, Bill Mill <bill.mill at gmail.com> wrote:
>>+1 . I think that we should still have the form [genexp] , but without
>>the dangling variable, and implemented with generator expressions. It
>>seems to me that it is inconsistent if I can do list(genexp) but not
>>[genexp] , since they are so similar. Once that happens, we can tell
>>people who ask the OP's question that [genexp] is just another way to
>>spell list(genexp), and he should use it if he wants the entire list
>>constructed in memory.
> ISTM you have to account for
>
>  >>> def foo(g): return g
>  ...
>  >>> foo(123)
>  123
>  >>> foo(c for c in 'abc')
>  <generator object at 0x02EF154C>
>  >>> [(c for c in 'abc')]
>  [<generator object at 0x02EF158C>]
>  >>> [c for c in 'abc']
>  ['a', 'b', 'c']

Right. But that shouldn't be hard to do. Let genexp stand for a a
generator expression/list comprehension without any brackets on it at
all. Then [genexp] is the syntax to expand the list. [(genexp)] is the
syntax to create a list of one element - a generator
object. foo(genexp) will do the right thing.

The question under these circumstances is then: do you want bare
genexp to mean something? Right now, it's a syntax error. But there's
no reason you couldn't have:

   y = x for x in stuff

assign a generator object to y.

       <mike
-- 
Mike Meyer <mwm at mired.org>			http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.



More information about the Python-list mailing list