Convenient filtering in for cycles
Ian Kelly
ian.g.kelly at gmail.com
Wed Oct 5 13:24:51 EDT 2011
On Wed, Oct 5, 2011 at 10:55 AM, Stefano Maggiolo <s.maggiolo at gmail.com> wrote:
> 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)
> ======
for x in filter(P, l):
do_stuff(x)
This works nicely if P is a function but can be a bit unwieldy if you
want to use an arbitrary expression, since you would need to put it in
a lambda.
> Is there some better and valid construction I missed? If not, is there
> a reason why (2) is not in the language?
I guess because, as you helpfully enumerated, there are already plenty
of options for iterating with a condition. Syntax isn't added without
a strong reason, and avoiding an extra line or an extra indentation
level isn't enough.
Cheers,
Ian
More information about the Python-list
mailing list