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

Chris Angelico rosuav at gmail.com
Sun Feb 25 07:46:28 EST 2018


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". But if you allow this in a comprehension, the
obvious next step will be "do we allow this in ANY expression?", and
the answer has to either be "yes" or "no, because {reasons}" for some
very good value of 'reasons'.

ChrisA


More information about the Python-Dev mailing list