[Python-3000] Using *a for packing in lists and other places
Arnaud Delobelle
arnodel at googlemail.com
Sun Mar 16 07:58:24 CET 2008
On 15 Mar 2008, at 16:15, Guido van Rossum wrote:
> Thomas Wouters suggests some new syntax:
>
> http://bugs.python.org/issue2292
>
>>>> a, b, *c = range(5)
>
>>>> *a, b, c = a, b, *c
>>>> a, b, c
> ([0, 1, 2], 3, 4)
>>>> [ *a, b, c ]
> [0, 1, 2, 3, 4]
>>>> L = [ a, (3, 4), {5}, {6: None}, (i for i in range(7, 10)) ]
>>>> [ *item for item in L ]
> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>
> Also, yielding everything from an iterator:
>
>>>> def flatten(iterables):
> ... for it in iterables:
> ... yield *it
> ...
>>>> L = [ a, (3, 4), {5}, {6: None}, (i for i in range(7, 10)) ]
>>>> flatten(L)
> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>
> What do people think?
With this syntax, one will be able to write:
>>> t = (1, 2, 3)
>>> [*t]
[1, 2, 3]
>>> {*t}
{1, 2, 3}
Will these become idioms replacing list(), tuple(), set()?
Moreover the '*' also competes with the '+' operator:
>>> t = (1, 2)
>>> l = [1, 3]
>>> [*t, *l] # replaces list(t) + l
[1, 2, 1, 3]
>>> {*t, *l} # replaces set(t) + set(l)
{1, 2, 3}
>>> (*t, *l) # replaces t + tuple(l)
(1, 2, 1, 3)
It is more versatile because, for example, t + l wouldn't work. I
don't know how desirable it is.
--
Arnaud
More information about the Python-3000
mailing list