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

Arnaud Delobelle arnodel at googlemail.com
Fri Jun 19 21:12:51 CEST 2009


On 18 Jun 2009, at 21:19, Lie Ryan wrote:

> 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.
>
> Even if f() is not a function such as
>
> [x + 1 for x in l if x + 1 > 0]
>
> it looks ugly since we're repeating ourself.
>
> We can work around it like this:
>
> [y for y in (f(x) for x in l) if y > 0]
>
> but then we have an unnecessary nested loop comprehension

You can write:

     [y for x in l for y in [f(x)] if y > 0]

Which is even worse ;)

-- 
Arnaud




More information about the Python-ideas mailing list