[Python-ideas] if in for-loop statement

Chris Angelico rosuav at gmail.com
Thu Feb 23 23:45:17 EST 2017


On Fri, Feb 24, 2017 at 3:28 PM, Steven D'Aprano <steve at pearwood.info> wrote:
> There is nothing wrong with a nested for...if pair of statements. But
> that does take two lines, and two indents, rather than one:
>
>     block
>     for ...
>         if ...
>             block
>
> versus hypothetical:
>
>     block
>     for ... if ...
>         block
>
>
> The proposed syntax saves one line, and one indent. That is a saving,
> but it is not a big saving. If one line and one indent *really* makes a
> difference to a piece of code, it is probably because you are already
> deeply nested:
>
>     class ...
>         def ...
>              def ...
>                  try ...
>                      try ...
>                          while ...
>                              try ...
>                                  if ...
>                                      with ...
>                                          if ...
>                                              while ...
>                                                  for ...
>                                                      if ...
>                                                          # not enough
>                                                          # room here

Don't forget that you can rewrite a "for-if" using two additional
lines and no indents, rather than one line and one indent:

for ...:
    if not (...):
        continue
    ...
    ...

So you can take your pick which version you want. Granted, I can still
see value in the for-if statement, but not enough to justify new
syntax.

ChrisA


More information about the Python-ideas mailing list