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.
In python tuples can be unpacked using a function in function tuple is passed and in function values are unpacked into normal variable.
Unpacking in Python refers to an operation that consists of assigning an iterable of values to a tuple (or list ) of variables in a single assignment statement. As a complement, the term packing can be used when we collect several values in a single variable using the iterable unpacking operator, * .
We can use * to unpack the list so that all elements of it can be passed as different parameters.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With