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

Therefore, apparently, I cannot 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 I ask

  • Is there any reason not to allow this? (first)
  • what's the closest thing that works?

My current guess for # 2:

 (a, b, c) = x + (3,) (a, b, c, d) = x + x (a, b, c, d) = x + tuple(y) 
+7
python
source share
3 answers

In response to question 1, read PEP 448 and error 2292 . Also interesting is the discussion on the mailing list. In summary, what you want should be allowed in Python 3.4. For question 2, see Other Solutions.

+8
source share

Do not forget itertools. This is usually more readable as the situation becomes 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) 
+2
source share

What you can do in Python 2.7:

 (a, b), c = x, 3 
+1
source share

All Articles