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

Steven D'Aprano steve at pearwood.info
Fri Jun 19 16:35:49 CEST 2009

On Fri, 19 Jun 2009 05:39:32 pm Lie Ryan wrote:
> Aahz wrote:
> > On Fri, Jun 19, 2009, 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.
> >
> > Listcomps and genexps are like lambdas: run up against their limits
> > and you should switch to a regular for loop or generator.
> I think of it not as limitation but as an odd gap in functionality. I
> think having the semantics that the filtering is done after the
> expression part would be much more useful than the current behavior
> (filtering before expression).

The point of the filtering is to avoid needlessly calculating a 
potentially expensive expression only to throw it away.

If you want expression first, then filter, you can get that already in a 

filter(lambda x: x > 0, [f(x) for x in seq])

Don't create new syntax when there are perfectly good functions that do 
the job already.

Steven D'Aprano

More information about the Python-ideas mailing list