conditional for-statement

seb sdementen at gmail.com
Tue Aug 25 21:58:38 CEST 2009


On Aug 25, 9:42 pm, Falcolas <garri... at gmail.com> wrote:
> On Aug 25, 11:25 am, seb <sdemen... at gmail.com> wrote:
>
>
>
> > We could as consistenly explain that the syntax
>
> > for n in range(10) if n%3==0:
> >   body
>
> > means
>
> > for n in range(10):
> >   if n%3==0:
> >     body
>
> > This syntax has also the benefit of avoiding an extra level of
> > indentation (the one for the if) that bears no real meaning on a
> > structural level.
>
> > Maybe a PEP could do the job...
>
> > Sébastien

>
> So, what part of the statement does the "if" statement belong to;
> particularly a concern considering this is valid python:
>
> for x in y if y else z:
>     body
>
can this be done in list/set/dict comprehensions/generator
expressions ?

> You can always do the following at the cost of 6 symbols, and the gain
> of clarity:
>
> for n in (x for x in y if y%3==0):
>     body

it is in fact precisely to avoid this sort of line:
  for n in (x for x in y if x%3==0):
and have instead the (more readable IMO) line
  for n in y if n%3==0:
with:
 - 1 "for ... in ..." instead of 2 (where one is the repetition of the
other)
 - no parentheses
 - no extra technical variable with local binding to the expression
generator ('x')
it looks more pythonic to me but it is a personal taste.

>
> ~G




More information about the Python-list mailing list