Is there a more elegant way to spell this?

Neal Becker ndbecker2 at gmail.com
Tue Jan 27 19:25:54 CET 2015


Jussi Piitulainen wrote:

> 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.


To clarify, I meant some_predicate(_), and then ifilter looks like a nice 
solution.

-- 
-- Those who don't understand recursion are doomed to repeat it




More information about the Python-list mailing list