[Python-ideas] Fwd: Fwd: unpacking generalisations for list comprehension

Martti Kühne mar77i at mar77i.ch
Thu Oct 13 14:15:36 EDT 2016


On Thu, Oct 13, 2016 at 6:55 PM, Steven D'Aprano <steve at pearwood.info> wrote:
> On Thu, Oct 13, 2016 at 04:34:49PM +0200, Martti Kühne wrote:
>
>> > If I had seen a list comprehension with an unpacked loop variable:
>> >
>> >     [t for t in [(1, 'a'), (2, 'b'), (3, 'c')]]
>
> Martti, somehow you have lost the leading * when quoting me. What I
> actually wrote was:
>
>     [*t for t in [(1, 'a'), (2, 'b'), (3, 'c')]]
>

Sorry for misquoting you. Can I fix my name, though?
Also, this mail was too long in my outbox so the context was lost on it.
I reiterate it, risking that I would annoy some, but to be absolutely clear.

>
>> As it happens, python does have an external consumption operation that
>> happens externally with an iteration implied:
>>
>
> If you replace the t with *t, you get a syntax error:
>

I meant that statement in context of the examples which were brought up:
the occurrence of a list comprehension inside an array have the
following effect:

1) [ ..., [expr for t in iterable] ]

is equivalent to:

def expr_long(iterable, result):
    result.append(iterable)
    return result

expr_long(iterable, [ ..., ])

so, if you make the case for pep448, you might arrive at the following:

2) [ ..., *[expr for expr in iterable] ]

which would be, if I'm typing it correctly, equivalent to, what
resembles an external collection:

def expr_star(list_comp, result):
    result.extend(list(list_comp))
    return result

expr_star(iterable, [ ..., ])

Having this in mind, the step to making:

[ ..., [*expr for expr in iterable], ]

from:

def expr_insidestar(iterable, result):
    for expr in iterable:
        result.extend(expr)
    return result

does not appear particularly far-fetched, at least not to me and a few
people on this list.

cheers!
mar77i


More information about the Python-ideas mailing list