Is there a more elegant way to spell this?

Jussi Piitulainen jpiitula at ling.helsinki.fi
Tue Jan 27 09:25:21 EST 2015


Neal Becker writes:

> Is there a more elegant way to spell this?
> 
> for x in [_ for _ in seq if some_predicate]:

If you mean some_predicate(_), then possibly this.

for x in filter(some_predicate, seq):
   handle(x)

If you mean literally some_predicate, then perhaps this.

if some_predicate:
   for x in seq:
      handle(x)

Unless you also have in mind an interesting arrangement where
some_predicate might change during the loop, like this.

for x in [_ for _ in seq if some_predicate]:
    ...
    some_predicate = fubar(x)
    ...

Then I have nothing to say.



More information about the Python-list mailing list