[Python-ideas] Accessing the result of comprehension's expression from the conditional
taleinat at gmail.com
Fri Jun 19 13:34:03 CEST 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.
> 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?
IMO this is premature optimization. (I know that's an annoying thing
to say, but bear with me...)
Just using [f(x) for x in nums if f(x) > 0] is the most readable and
obvious option. I think the case where such a line of code actually
needs to be optimized is rare, and on there rare occasions using a
slightly less readable variant is reasonable (along with an insightful
In other words, from my experience all we would gain from the proposed
new syntax is making such premature optimization easier, at the cost
of less readable code and more complex syntax.
More information about the Python-ideas