Let's now write functions to sum lists recursively. Here is the first option:
def sum_list(L):
'''Return the sum of the list of ints L'''
if len(L) == 0:
return 0
return L[0] + sum_list(L[1:])
The idea here is very similar to printing the list L -- we assume the function works, define a base case, and proceed by computing the sum by adding L[0] and the sum of the rest of the list (L[1:]).
Here's another idea: let's sum up the first half of the list and the second half of the list:
def sum_list2(L):
'''Return the sum of the list of ints L'''
if len(L) == 0:
return 0
if len(L) == 1:
return L[0] #the sum of the list is L[0] if L[0] is the only element
mid = len(L)//2 #(the index of the approximate midpoint of the list)
return sum_list2(L[:mid]) + sum_list2(L[mid:])
In sum_list2, we had to have two base cases. That's because of what happens when the length of the list is 1. We' would have computed mid = 1//2 == 0, which would mean that the first "half" of the list would be L[:0] (i.e., []), and the second "half" of the list would be L[0:], i.e., just a copy of L. That would result in infinite recursion if we didn't return right away when we see that the length of the list is 1.