conditional for-statement

seb sdementen at gmail.com
Tue Aug 25 17:19:31 EDT 2009


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

I never thought about this case...
Testing that in python 3.0, i see that

>>> [x for x in range(5) if False else range(10)]
SyntaxError: invalid syntax (<pyshell#17>, line 1)
>>> [x for x in (range(5) if False else range(10))]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

hence, to avoid the ambiguity you mentionned (that already exists with
list comprehensions), one can use the parenthesis. This minor
incompatibility is referenced in http://www.python.org/dev/peps/pep-0308/

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

in my mind, I am thinking as you are but with 'loop' instead of
'stream'
"""so you can filter the 'loop' before acting on it. One statement
performs one action - very precise and understandable."""
and it doesn't look that dissimilar to your own reasoning.

>
> 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.
>
before having list comprehensions, we could also have said that
"""  I would not agree that adding a 'list comprehension' feature is
required. Not when we have the filter
     function, and the 'for+if' statements which all provide that very
functionality."""

How can unifying the "for ... in ..." statement with the "for ...
in ... if ..." syntax be detrimental ? It would be an inconsistence
less to remember, wouldn't it ?

cheers,

sebastien



More information about the Python-list mailing list