Uri Goren Uri Goren - 18 days ago 6
Python Question

Increase the last element in a tuple

I want to implement a function that takes a

tuple
of
int
s and increases the last element by 1:

inc((0,0,0,1))==(0,0,0,2)
inc((1,2,3))==(1,2,4)


This is what I came up with:

def inc(t):
l=list(t)
l[-1]+=1
return tuple(l)


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

jez jez
Answer

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.