Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: why not (a, b, c) = (*x, 3)

Tags:

python

So apparently I can't do this in Python (2.7):

x = (1, 2,)
(a, b, c) = (*x, 3)

It made sense in my head, but well... I could create a function:

make_tuple = lambda *elements: tuple(elements)

then I can do

(c, a, b) = make_tuple(3, *x)

but not, for example

(a, b, c) = make_tuple(*x, 3)
(a, b, c, d) = make_tuple(*x, *x)
y = [3, 4]
(a, b, c, d) = (*x, *y,)

So what I am asking is

  1. is there a reason for not allowing this? (the first thing)
  2. what is the closest thing that does work?

My current guess for #2:

(a, b, c) = x + (3,)
(a, b, c, d) = x + x
(a, b, c, d) = x + tuple(y)
like image 609
Mark Avatar asked Oct 01 '13 05:10

Mark


3 Answers

In response to question 1, read the PEP 448 and bug 2292. Also interesting is the discussion in the mailing list. In resume what you want should be allowed in Python 3.4. For question 2 see the other solutions.

like image 54
elyase Avatar answered Nov 16 '22 00:11

elyase


Don't forget itertools. It's usually more readable as things get more complex

>>> from itertools import chain
>>> a,b,c = chain(x, (3,))
>>> a,b,c,d = chain(x, x)
>>> a,b,c,d = chain(x, y)
like image 2
John La Rooy Avatar answered Nov 15 '22 23:11

John La Rooy


What you can do in Python 2.7 is:

(a, b), c = x, 3
like image 1
Marius Avatar answered Nov 16 '22 00:11

Marius