tags:

views:

162

answers:

3

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)

+7  A: 
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.

Ivo
How about `(a[-1] * 2,)`? The above throws a TypeError. (the trailing comma is necessary for a one-item tuple)
Skilldrick
@Skilldrick thanks, edited
Ivo
+5  A: 

I would do something like:

b=list(a)
b[-1]*=2
b=tuple(b)
DiggyF
+1: this is quite legible, and flexible.
EOL
+4  A: 

Here's one way of doing it:

>>> a = (1, 2, 3, 4)
>>> b = a[:-1] + (a[-1]*2, )
>>> a
(1, 2, 3, 4)
>>> b
(1, 2, 3, 8)

So what happens on the second line? a[:-1] means all of a except the last element. a[-1] is the last element, and we multiply it by two. The (a[-1]*2, ) turns the result into a tuple, and the sliced tuple is concatenated with it using the + operator. The result is put in b.

You can probably fit this to your specific case.

Fabian Fagerholm