
Steven D'Aprano wrote:
On Fri, 19 Jun 2009 05:39:32 pm Lie Ryan 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
Aahz wrote: 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 one-liner:
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.
That's ugly because of the same reason for using map(): [y for y in map(lambda x: f(x), seq) if y > 0] or nested comprehension: [y for y in (f(x) for x in seq) if y > 0]