4.3. Calculating the Sum of a List of Numbers¶
We will begin our investigation with a simple problem that you already
know how to solve without using recursion. Suppose that you want to
calculate the sum of a list of numbers such as:
the_sum
) to compute a running total of all the numbers in the list
by starting with
Pretend for a minute that you do not have while
loops or for
loops. How would you compute the sum of a list of numbers? If you were a
mathematician you might start by recalling that addition is a function
that is defined for two parameters, a pair of numbers. To redefine the
problem from adding a list to adding pairs of numbers, we could rewrite
the list as a fully parenthesized expression. Such an expression looks
like this:
We can also parenthesize the expression the other way around,
Notice that the innermost set of
parentheses,
How can we take this idea and turn it into a Python program? First,
let’s restate the sum problem in terms of Python lists. We might say
the sum of the list num_list
is the sum of the first element of the
list (num_list[0]
) and the sum of the numbers in the rest of the
list (num_list[1:]
). To state it in a functional form:
In this equation
There are a few key ideas in this listing to look at. First, on line 2 we are checking to see if the list is one element long. This
check is crucial and is our escape clause from the function. The sum of
a list of length 1 is trivial; it is just the number in the list.
Second, on line 5 our function calls itself! This is the
reason that we call the list_sum
algorithm recursive. A recursive
function is a function that calls itself.
Figure 4.1 shows the series of recursive calls that are
needed to sum the list
Figure 4.1: Series of Recursive Calls Adding a List of Numbers

When we reach the point where the problem is as simple as it can get, we
begin to piece together the solutions of each of the small problems
until the initial problem is solved. Figure 4.2 shows the
additions that are performed as list_sum
works its way backward
through the series of calls. When list_sum
returns from the topmost
problem, we have the solution to the whole problem.
Figure 4.2: Series of Recursive Returns from Adding a List of Numbers
