Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 461
cfi Avatar asked Sep 19 '12 10:09

cfi


People also ask

Can tuple be unpacked?

In python tuples can be unpacked using a function in function tuple is passed and in function values are unpacked into normal variable.

How does tuple unpacking work in Python?

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, * .

Can we do unpacking of list in Python?

We can use * to unpack the list so that all elements of it can be passed as different parameters.


4 Answers

You could use add operator:

a = [3, 4]
b = [1, 2] + a
like image 130
pr0gg3d Avatar answered Oct 12 '22 22:10

pr0gg3d


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.

like image 38
mgilson Avatar answered Oct 12 '22 23:10

mgilson


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
like image 22
Martijn Pieters Avatar answered Oct 12 '22 22:10

Martijn Pieters


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

>>> a=[3,4]
>>> b=[1,2,*a]
>>> b
[1, 2, 3, 4]
like image 20
Deqing Avatar answered Oct 12 '22 22:10

Deqing