Uri Goren Uri Goren - 1 year ago 93
Python Question

Increase the last element in a tuple

I want to implement a function that takes a

s and increases the last element by 1:


This is what I came up with:

def inc(t):
return tuple(l)

Can this be done in a more compact way (and maybe without the conversion to list) ?

jez jez
Answer Source

A tuple cannot be modified in-place. If it's very important to use the tuple type rather than a mutable sequence, then the following code will do what you want without converting:

def inc(t):
    return t[:-1] + (t[-1] + 1,)

Note that it has to create three new tuples in order to accomplish this. I don't know that the overhead involved in that is going to be any smaller than the overhead in converting to & from list.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download