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

Georg Brandl g.brandl at gmx.net
Sun Jan 11 10:14:41 CET 2009


Gerald Britton schrieb:
> Hmmm.  I can't really see what you are saying.  Your example doesn't
> quite get the intention.  The "while" clause in the example would
> translate like this:
> 
>      def gen():
>          for i in range(100):
>              if i <= 50:
>                  yield i
>              else:
>                 break
> 
> Also, I think that for a new python user,
> 
> (n for n in range(100) while n*n < 50)
> 
> is easier to understand and use than:
> 
> (n for n in takewhile(lambda n:n*n < 50, range(100)))
>
> My proposed version is shorter (less chance for typos), has one less
> set of parentheses (always a good thing) and reads naturally.

The other is needlessly complicated, though.

takewhile(lambda n: n*n < 50, range(100))

is just as fine, and only 3 characters longer than the proposed while-exp.

Georg

-- 
Thus spake the Lord: Thou shalt indent with four spaces. No more, no less.
Four shall be the number of spaces thou shalt indent, and the number of thy
indenting shall be four. Eight shalt thou not indent, nor either indent thou
two, excepting that thou then proceed to four. Tabs are right out.




More information about the Python-ideas mailing list