[Python-ideas] Accessing the result of comprehension's expression from the conditional

Lie Ryan lie.1296 at gmail.com
Fri Jun 19 09:01:13 CEST 2009

Paul Moore wrote:
> 2009/6/18 Lie Ryan <lie.1296 at gmail.com>:
>> In list/generator comprehension, currently we have no way to access the
>> result of the expression and have to write something like this:
>> [f(x) for x in l if f(x) > 0]
>> if f() is heavy or non-pure (i.e. have side effects), calling f() twice
>> might be undesirable.
> [y for y in (f(x) for x in l) if y > 0]
> But as Aahz says, if it's too complex, use an explicit loop. Not
> everything needs to be a one-liner.
> Paul

Avoiding a nested list comprehension is exactly the motivation for the idea.

More information about the Python-ideas mailing list