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

Steven D'Aprano steve at pearwood.info
Sat Oct 15 06:48:40 EDT 2016


On Sat, Oct 15, 2016 at 11:36:28PM +1300, Greg Ewing wrote:

> Indeed. In situations where there isn't any context for
> the interpretation of *, it's not allowed. 

You mean like in list comprehensions?

Are you now supporting my argument that starring the list comprehension 
expression isn't meaningful? Not if star is defined as sequence 
unpacking in the usual way. If you want to invent a new meaning for * to 
make this work, to join all the other special case magic meanings for 
the * symbol, that's another story.


> For example:
> 
> >>> x = *(1, 2, 3)
>   File "<stdin>", line 1
> SyntaxError: can't use starred expression here
> 
> But
> 
> >>> x = 1, *(2, 3)
> >>> x
> (1, 2, 3)
> 
> The * is allowed there because it's already in a context
> where a comma-separated list has meaning.

Oh look, just like now:

py> iterable = [(1, 'a'), (2, 'b')]
py> [(100, *t) for t in iterable]
[(100, 1, 'a'), (100, 2, 'b')]

Hands up anyone who expected to flatten the iterable and get 

    [100, 1, 'a', 100, 2, 'b']

instead? Anyone? No?

Take out the (100, ...) and just leave the *t, and why should it be 
different? It is my position that:

    (quote)
    there isn't any context for the interpretation of *

for [*t for t in iterable]. Writing that is the list comp equivalent of 
writing x = *t.


-- 
Steve


More information about the Python-ideas mailing list