Convenient filtering in for cycles

Stefano Maggiolo s.maggiolo at gmail.com
Wed Oct 5 12:55:53 EDT 2011


Dear all,

I would like to know if there is a (more) convenient way of doing this
structure:

===(1)===
for x in l:
    if P(x):
        do_stuff(x)
======

Let's say that my dream syntax would be

===(2)===
for x in l if P(x):
    do_stuff(x)
======

as if it was the second part of a list comprehension. But sadly it is
not in the language. Obvious alternatives are

===(3)===
for x in (x for x in l if P(x)):
    do_stuff(x)
======

===(4)===
for x in l:
    if not P(x):
        continue
    do_stuff(x)
======

===(5)===
[do_stuff(x) for x in l if P(x)]
======

As I see it, every syntax-valid solution has its drawbacks:
(1) adds an indentation level;
(3) adds an unnatural repetition of variable names and "for";
(4) has the "masked goto" continue (even if it is quite easy to
understand what happens);
(5) is good but not usable when do_stuff is what it usually is, that
is a list of instructions.

Is there some better and valid construction I missed? If not, is there
a reason why (2) is not in the language?

Pardon my boldness, but I am asking this because there are two invalid
construct that I keep writing when I don't pay attention: one is (2),
and the other is list comprehensions as in

===(6)===
for x in (x in l if P(x)):
    do_stuff(x)
======

which accidentally would be a better solution than (1), (3), (4), (5),
though not as good as (2).

Thank you for your attention,
Stefano Maggiolo



More information about the Python-list mailing list