For loop comprehensions

Benjamin S Wolf bswolf at google.com
Sat Feb 12 09:27:43 CET 2011


On Feb 11, 3:47 pm, Westley Martínez <aniko... at gmail.com> wrote:
> No, too confusing. Then people'll want compound loops e.g.:
>
> for a in b if c while d else return x:
>     print('Ha ha I'm so clever!')

On Feb 11, 6:34 pm, Steven D'Aprano <steve
+comp.lang.pyt... at pearwood.info> wrote:
> There's nothing wrong with writing
>
> for x in iterable:
>     if condition(x):
>         process(x)
>
> The existing syntax is clear and obvious. There's no clear benefit to
> shifting the if clause to the for expression: it complicates the parser,
> and any benefit (if any!) only applies to a tiny fraction of for loops.
> You save one line, which is trivial. You may save one indentation level,
> which might, sometimes, be useful, but more often will also be trivial.
> If there's an advantage to the suggestion, it's small.

My reasons for suggesting this are more to align for-loop syntax with
generator expression/list comprehension syntax than to add completely
new functionality to for-loops. I had observed that what I had typed
initially before realizing it was incorrect:

  for a in b if c:
    f(a)

was equivalent (and nearly syntactically so) to

  [f(a) for a in b if c]

minus the generation of a list.

I understand there are more verbose ways to accomplish the same goal
(such as filter or multiple lines). But there are also more verbose
ways to construct a list (such as filter or multiple lines). That is
why I decided to suggest it.

On Feb 11, 7:54 pm, Terry Reedy <tjre... at udel.edu> wrote:
> Already proposed and rejected. See archives for python-ideas or the
> gmane.comp.python.ideas mirror.

Thanks for pointing me in the right direction, and sorry for bringing
it up a third (if not more!) time.

For posterity, http://groups.google.com/group/python-ideas/browse_thread/thread/87eee156ac2c3a24/61621e7779b5b255,
and earlier, http://groups.google.com/group/python-ideas/browse_thread/thread/e2d076fe35ece873/862674672b4de683.

The latter brings up a good point about parsing: how will we be sure
after reading 'for a in b if c' whether this is a comprehension or
whether (b if c) begins a ternary expression (and we should expect a
'else d' to follow). Well, my suggestion is to bring for-loop syntax
in line with comprehension syntax, and:

>>> [a for a in range(10) if False else [99]]
SyntaxError: invalid syntax
>>> [a for a in (range(10) if False else [99])]
[99]
>>> for a in range(10) if False else [99]:
	print(a)
...
99

So as it stands now in 3.1, comprehensions don't permit the ternary
expression without parenthesizing it, but for-loops do. So my
suggestion would have the side effect of requiring parentheses for
that latter expression, as comprehensions do. :/

Thanks again,
--Ben



More information about the Python-list mailing list