Search code examples
pythonpython-3.xpython-3.2iterable-unpacking

Tuple unpacking in list construction (python3)


I'd love to use tuple unpacking on the right hand side in assignments:

>>> a = [3,4]

>>> b = [1,2,*a]
  File "<stdin>", line 1
SyntaxError: can use starred expression only as assignment target

OF course, I can do:

>>> b = [1,2]
>>> b.extend(a)
>>> b
[1, 2, 3, 4]

But I consider this cumbersome. Am I mising a point? An easy way? Is it planned to have this? Or is there a reason for explicitly not having it in the language?

Part of the problem is that all container types use a constructor which expect an iterable and do not accept a *args argument. I could subclass, but that's introducing some non-pythonic noise to scripts that others are supposed to read.


Solution

  • This is fixed in Python 3.5 as described in PEP 448:

    >>> a=[3,4]
    >>> b=[1,2,*a]
    >>> b
    [1, 2, 3, 4]