Sometimes you need to pass extra state through recursive calls. Use helper parameters.
def sum_list_helper(lst, index, total):
if index >= len(lst):
return total
return sum_list_helper(lst, index + 1, total + lst[index])
def sum_list(lst):
return sum_list_helper(lst, 0, 0)
print(sum_list([1, 2, 3, 4])) # 10
Here index tracks position and total accumulates the sum. The helper function does the work, the wrapper provides initial values. This runs in time and uses space for the call stack. It avoids creating new lists with slicing, which would add per call.