Reputation: 11290
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.
Upvotes: 5
Views: 1942
Reputation: 14632
This is fixed in Python 3.5 as described in PEP 448:
>>> a=[3,4]
>>> b=[1,2,*a]
>>> b
[1, 2, 3, 4]
Upvotes: 3
Reputation: 309899
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.
Upvotes: 7
Reputation: 1121744
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
Upvotes: 4