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

Chris Rebert pyideas at rebertia.com
Fri Jun 19 10:04:18 CEST 2009

On Fri, Jun 19, 2009 at 12:39 AM, Lie Ryan<lie.1296 at gmail.com> 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).
> If filtering is done after expression, we can access both the original
> and the transformed objects (it may also be possible to optimize the
> cases where the filter does not use the transformed objects, although
> this complex behavior wouldn't be pythonic)
> Try rewriting this:
> res = [x**x as F for x in nums if F < 100]
> (note: this is my new preferred syntax)
> Attempts:
> - Using a regular for-loop
> res = []
> for x in nums:
>    F = x**x
>    if F < 100:
>        res.append(F)
> remarks: five lines that's much more difficult to understand than a
> single, concise expression in standard form.

Depends on how complicated the "standard form" is; right now, it (list
comps) is/are relatively simple. Perl syntax is concise and adheres to
a standard, but is not easy to understand.
Not to equate a minor syntax addition to Perl, but every addition is a
step in that general direction. The road to hell was paved with good


More information about the Python-ideas mailing list