[Python-Dev] The `for y in [x]` idiom in comprehensions

Nikolaus Rath Nikolaus at rath.org
Sun Feb 25 08:11:05 EST 2018


On Feb 25 2018, Chris Angelico <rosuav at gmail.com> wrote:
> On Sun, Feb 25, 2018 at 11:02 PM, Nikolaus Rath <Nikolaus at rath.org> wrote:
>> On Feb 22 2018, Serhiy Storchaka <storchaka at gmail.com> wrote:
>>> 1. Inner generator expression:
>>>
>>>     result = [y + g(y) for y in (f(x) for x in range(10))]
>>>
>> [...]
>>>
>>> And maybe there are other ways.
>>
>> I think the syntax recently brough up by Nick is still the most
>> beautiful:
>>
>>     result = [ (f(x) as y) + g(y) for x in range(10)]
>>
>> ..but I wonder if it is feasible to make the interpreter sufficiently
>> smart to evaluate the first summand before the second.
>
> It already has to. The order of evaluation in Python is well defined,
> mostly "left to right".

Ah, then the problem is how to evaluate

    result = [ y + g(f(x) as y) for x in range(10)]

I don't think there'd be a good reason to allow one but not the other.

> But if you allow this in a comprehension, the
> obvious next step will be "do we allow this in ANY expression?"

Yes, of course. After all, IIRC Nick proposed it to simplify ternary
expressions.


Best,
-Nikolaus

-- 
GPG Fingerprint: ED31 791B 2C5C 1613 AF38 8B8A D113 FCAC 3C4E 599F

             »Time flies like an arrow, fruit flies like a Banana.«


More information about the Python-Dev mailing list