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

Georg Brandl g.brandl at gmx.net
Sat Jun 20 10:13:06 CEST 2009

Lie Ryan schrieb:
> Steven D'Aprano wrote:
>> 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 
>> 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]

Especially if f is already a handy callable of one argument, no need to use
a lambda.


Thus spake the Lord: Thou shalt indent with four spaces. No more, no less.
Four shall be the number of spaces thou shalt indent, and the number of thy
indenting shall be four. Eight shalt thou not indent, nor either indent thou
two, excepting that thou then proceed to four. Tabs are right out.

More information about the Python-ideas mailing list