Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: how to change (last) element of tuple?

Tags:

python

The question is a bit misleading, because a tuple is immutable. What I want is:

Having a tuple a = (1, 2, 3, 4) get a tuple b that is exactly like a except for the last argument which is, say, twice the last element of a.

=> b == (1, 2, 3, 8)

like image 366
Cristian Diaconescu Avatar asked Aug 06 '10 14:08

Cristian Diaconescu


1 Answers

b = a[:-1] + (a[-1]*2,)

What I'm doing here is concatenation of two tuples, the first containing everything but the last element, and a new tuple containing the mutation of the final element. The result is a new tuple containing what you want.

Note that for + to return a tuple, both operands must be a tuple.

like image 60
Ivo Avatar answered Nov 12 '22 21:11

Ivo