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

Lie Ryan lie.1296 at gmail.com
Thu Jun 18 22:19:01 CEST 2009

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.

I'm suggesting about something like:

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

where @ is the result of the listcomp's expression (i.e. f(x))

Personally, I don't like the use of symbols like @, as python is not
perl. I'm still thinking of a better syntax/approach and is open for

What do you guys think?

More information about the Python-ideas mailing list