1

I want to implement a function that takes a tuple of ints 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) ?

Uri Goren
  • 13,386
  • 6
  • 58
  • 110

1 Answers1

3

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.

jez
  • 14,867
  • 5
  • 37
  • 64