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

Steven D'Aprano steve at pearwood.info
Thu Oct 13 12:55:46 EDT 2016


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')]]

Marttii, somehow you have lost the leading * when quoting me. What I 
actually wrote was:

    [*t for t in [(1, 'a'), (2, 'b'), (3, 'c')]]


> As it happens, python does have an external consumption operation that
> happens externally with an iteration implied:
> 
> for t in iterable:
>     yield t

If you replace the t with *t, you get a syntax error:


py> def gen():
...     for t in [(1, 'a'), (2, 'b'), (3, 'c')]:
...             yield *t
  File "<stdin>", line 3
    yield *t
          ^
SyntaxError: invalid syntax

Even if it was allowed, what would it mean? It could only mean "unpack 
the sequence t, and collect the values into a tuple; then yield the 
tuple".


 
> For your example [t for t in [(1, 'a'), (2, 'b'), (3, 'c')]] that would mean:
> 
> for t in [(1, 'a'), (2, 'b'), (3, 'c')]:
>     yield t
> 
> And accordingly, for the latter case [*t for t in [(1, 'a'), (2, 'b'),
> (3, 'c')]] it would be:
> 
> for item in [(1, 'a'), (2, 'b'), (3, 'c')]:
>     for t in item:
>         yield t

No it wouldn't. Where does the second for loop come from? The list 
comprehension shown only has one loop, not nested loops.



-- 
Steve


More information about the Python-ideas mailing list