x.pop(0)
will remove the first item and return it. And you are passing that to rsum
, which is trying to do x[0]
, but x
is now a number. That is why it is failing.
Instead, use pop
first, and the pass x
to rsum
like this
def rsum(x):
if not x:
return 0
else:
return x.pop() + rsum(x)
print rsum([1, 2, 3])
# 6
If you want to avoid mutating the original object, then use slicing to create new list without the first element, like this
def rsum(x):
if not x:
return 0
else:
return x[0] + rsum(x[1:])
print rsum([1, 2, 3])
# 6
Since you are learning recursion, I would like you to consider Tail Call optimization as well. You can change your function a little bit like this
def rsum(x, total):
if not x:
return total
else:
return rsum(x[1:], total + x[0])
print rsum([1, 2, 3], 0)
# 6
In earlier cases, till you hit your base condition (if not x:
) the current function cannot be taken out of the memory (because x[0]
or x.pop()
is in the current stack and they have to added with the result of the recursive call to actually return from the current function). So, when you run this function on a very large list, it will run out of stack space. But, in the TCO version, you are returning the result of another function call. So, the current function need not have to be in memory.
Note: That said, Python doesn't support Tail Call Optimization. Read what the BDFL (Guido) has to say about this here.