[Python-ideas] if-statement in for-loop

Alexander Heger python at 2sn.net
Fri Sep 30 20:25:29 EDT 2016


>
> for x in seq1 if p1(x)\
> for y in seq2 if p2(y)\
> for z in seq3 if p3(z):
>     result.append(f(x, y, z))
>

It think it is not uncommon to have nested loops, maybe with an if/continue
statement at the beginning, with only one logical block that then should go
down only one indentation level rather than three or four.

An alternate way may be

from itertools import product
for x,y,z in filter(lambda x:p1(x[0]) and p2(x[1]) and p3(x[2]), \
product(seq1, seq3, seq3)):
    do_stuff(x,y,z)

Doable, but seems kind of clunky.

As a note, in general p2 could depend on x and y and p3 and x,y, and z;
seq2 could depend on x and seq3 and x and y.  The latter is something my
example could not cover easily but only when explicitly writing out the
loop, either in comprehension-style or "classic" loops.

I think wasting of indentation levels for a single logical block should be
avoided if possible to make the code more legible, otherwise one hits the
suggested line length limit too fast - suppose this is now inside a method,
you already lose at least 8 char ...
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20161001/d0aaa7b6/attachment.html>


More information about the Python-ideas mailing list