conditional for-statement

Falcolas garrickp at
Tue Aug 25 22:46:19 CEST 2009

On Aug 25, 1:58 pm, seb <sdemen... at> wrote:
> On Aug 25, 9:42 pm, Falcolas <garri... at> wrote:
> > On Aug 25, 11:25 am, seb <sdemen... at> wrote:
> > 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 ?

It's a statement, so anywhere you use a statement (such as in
generators and list comprehensions), it can exist. for ... in ... only
requires that the statement return an iterable, it doesn't matter what
statement you use to get there.

For example, the following is perfectly valid (if nonsensical - I
don't use ternary operators very often in my programming, so I don't
have many good examples of their use)

list = [x if x else y for x, y in iterable]

> 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.

It doesn't feel clear to me, which is why I would have to disagree.
IIRC, these very filters are the main reason that list comprehensions,
and later one-line generators and dictionary comprehensions were
originally created: so you can filter the stream before acting on it.
One statement performs one action - very precise and understandable.

It's just my two cents, but I would not agree that adding a filter
keyword to for loops is required. Not when we have the filter
function, various types of comprehensions, and if statements which all
provide that very functionality.


More information about the Python-list mailing list