Generator Comprehensions

Bengt Richter bokr at
Tue Jan 29 09:10:46 EST 2002

On Tue, 29 Jan 2002 05:50:38 -0500, Oren Tirosh <oren-py-l at> wrote:

>On Mon, Jan 28, 2002 at 09:29:46PM -0500, Raymond Hettinger wrote:
>> Wild idea of the day:  Extend the syntax for list comprehensions
>> to have an optional 'yield' to create a generator rather than a list.
>> sizegen = [ yield (len(line),line) for line in file.readline() ]
>I like it.  Reusing the yield keyword is a very elegant solution.
>One problem with this syntax is that there is no justification for the use
>of square brackets - the result isn't a list.  It looks like it can work 
>just fine without them.  The keyword yield can work similarly to the 
>lambda keyword.  It would have a priority just between lambda and boolean 
For easier parsing, how about

    sizegen = yield.listcomp( (len(line),line) for line in file.readline() )

Bengt Richter

More information about the Python-list mailing list