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

MRAB python at mrabarnett.plus.com
Sat Jun 20 16:16:16 CEST 2009


Calvin Spealman wrote:
> On Sat, Jun 20, 2009 at 9:22 AM, MRAB<python at mrabarnett.plus.com> wrote:
>> Ben Finney wrote:
>>> Jim Jewett <jimjjewett at gmail.com> writes:
>>>
>>>> On Fri, Jun 19, 2009 at 3:39 AM, Lie Ryan<lie.1296 at gmail.com> wrote:
>>>>
>>>>> res = [x**x as F for x in nums if F < 100]
>>>> This, I have wanted.
>>> You have it:
>>>
>>>    res = [f for f in (x**x for x in nums) if f < 100]
>>>
>>> In addition to the fact that this works now in existing Python, I find
>>> it clearer than the above syntax you say you want.
>>>
>> How about:
>>
>>   res = [F for x in nums with x**x as F if F < 100]
>>
>> :-)
> 
> That toggles the first part of the comprehensions to be or not be an
> expression, depending on if there is a with clause later. You could
> miss this when you read it, and it opens the door to doing more
> strange things, like:
> 
>   res = [F/2 for x in nums with x**x as F if F < 100]
> 
> This is basically a strangely syntaxed nested loop
> 
I don't know what you mean.

 >>> def F(m, x):
	print m, x
	return x

 >>> [foo("value", x) for x in range(5) if foo("test", x) % 2]
test 0
test 1
value 1
test 2
test 3
value 3
test 4
[1, 3]

The test is done first, so it's equivalent to:

 >>> results = []
 >>> for x in range(5):
	if foo("test", x) % 2:
		results.append(foo("value", x))

		
test 0
test 1
value 1
test 2
test 3
value 3
test 4

That means that:

     res = [x**x for x in nums if x**x < 100]

is equivalent to:

     res = []
     for x in nums :
         if x**x < 100:
             res.append(x**x)

My suggestions turns:

     res = []
     for x in nums :
         F = x**x # <== temporary variable
         if F < 100:
             res.append(F)

into:

     res = [F for x in nums with x**x as F if F < 100]
                            ^^^^^^^^^^^^^^
                            temporary variable



More information about the Python-ideas mailing list