[Python-ideas] Add "while" clauses to generator expressions

Gerald Britton gerald.britton at gmail.com
Sat Jan 10 20:06:02 CET 2009

Yes of course. However I am advocating adding this to the syntax
rather than using the takewhile function, thus making it part of the
generator expression proper and avoiding the function call and module
include. From the little I know about the implementation of the
corresponding "if" clause, this should be relatively easy.

On 1/10/09, Mathias Panzenböck <grosser.meister.morti at gmx.net> wrote:
> Mathias Panzenböck schrieb:
>> Gerald Britton schrieb:
>>> I've been using Python generators for a while now.  e.g.
>>> a=(i for i in range(10))
>>> a.next()
>>> a.next()
>>> ...etc.
>>> I also find the "if" clause handy:
>>> a = (i for i in range(10) if i%2==0)
>>> (I know that range(0,12,2) will do the same thing, but it's the idea I
>>> like, especially for more complex predicates.)
>>> I would like to know if anyone has thought of adding a "while" clause
>>> as well, like this:
>>> a = (i for i in range(100) while i <=50)
>> from itertools takewhile
>> a = takewhile(lambda i: i <= 50, xrange(100))
> typo:
> from itertools import takewhile
> a = takewhile(lambda i: i <= 50, xrange(100))

Sent from my mobile device

More information about the Python-ideas mailing list