[Python-ideas] PEP 572: Statement-Local Name Bindings

Chris Angelico rosuav at gmail.com
Wed Feb 28 09:06:32 EST 2018


On Thu, Mar 1, 2018 at 12:49 AM, Serhiy Storchaka <storchaka at gmail.com> wrote:
> 28.02.18 00:27, Chris Angelico пише:
>>
>> Example usage
>> =============
>>
>> These list comprehensions are all approximately equivalent::
>>
>>      # Calling the function twice
>>      stuff = [[f(x), f(x)] for x in range(5)]
>
>
> The simplest equivalent of [f(x), f(x)] is [f(x)]*2. It would be worth to
> use less trivial example, e.g. f(x) + x/f(x).

Sure, I'll go with that.

>>      # Expanding the comprehension into a loop
>>      stuff = []
>>      for x in range(5):
>>          y = f(x)
>>          stuff.append([y, y])
>>
> Other options:
>
>     g = (f(x) for x in range(5))
>     stuff = [[y, y] for y in g]

That's the same as the one-liner, but with the genexp broken out. Not
sure it helps much as examples go?

>     def g():
>         for x in range(5):
>             y = f(x)
>             yield [y, y]
>     stuff = list(g)

You're not the first to mention this, but I thought it basically
equivalent to the "expand into a loop" form. Is it really beneficial
to expand it, not just into a loop, but into a generator function that
contains a loop?

ChrisA


More information about the Python-ideas mailing list