简体   繁体   中英

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.

You could use add operator:

a = [3, 4]
b = [1, 2] + a

You have a few options, but the best one is to use list concatenation ( + ):

b = [1,2] + a

If you really want to be able to use the * syntax, you can create your own list wrapper:

def my_list(*args):
    return list(args)

then you can call it as:

a = 3,4
b = my_list(1,2,*a)

I suppose the benefit here is that a doesn't need to be a list, it can be any Sequence type.

No, this is not planned. The *arg arbitrary parameter list (and **kw keyword arguments mapping) only applies to python call invocations (mirrored by *arg and **kw function signatures ), and to the left-hand side of an iterable assignment .

You can simply concatenate the two lists:

b = [10, 2] + a

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM