Math and Python: loops and summation

Published

2023-07-31

Calculating a sum in a loop

While we have the Python built-in function sum() which sums the elements of a sequence (provided the elements of the sequence are all of numeric type), it’s instructive to see how we can do this in a loop (in fact, summing in a loop is exactly what the sum() function does).

Here’s a simple example.

t = (27, 3, 19, 43, 11, 9, 31, 36, 75, 2)

sum_ = 0

for n in t:
    sum_ += n

print(sum_)             # prints 256
assert sum_ == sum(t)   # verify answer

We begin with a tuple of numeric values, t. Since the elements of t are all numeric, we can calculate their sum. First, we create a variable to hold the result of the sum. We call this, sum_.1 Then, we iterate over all the elements in t, and at each iteration of the loop, we add the value of each element to the variable sum_. Once the loop has terminated, sum_ holds the sum of all the elements of t. Then we print, and compare with the result returned by sum(t) to verify this is indeed the correct result.

In calculations like this we call the variable, sum_, an accumulator (because it accumulates the values of the elements in the iteration).

That’s how we calculate a sum in a loop!

Loops and summations

It is often the case that we have some formula which includes a summation, and we wish to implement the summation in Python.

For example, the formula for calculating the arithmetic mean of a list of numbers requires that we first sum all the numbers:

\begin{equation*} \mu = \frac{1}{N} \sum\limits^{N-1}_{i = 0} x_i \end{equation*}

If you’ve not seen the symbol \sum before, it’s just shorthand for “add them all up.”

What’s the connection between summations and loops? The summation is a loop!

In the formula above, there’s some list of values, x indexed by i. The summation says: “Take all the elements, x_i, and sum them.” The summation portion is just

\sum\limits^{N-1}_{i = 0} x_i

which is the same as

x_0 + x_1 + \ldots + x_{N-2} + x_{N-1}

Here’s the loop in Python (assuming we have some list called x):

s = 0
for e in x:
    s = s + e

after which, we’d divide by the number of elements in the list:

mean = s / len(x)

Yes, we could calculate the sum with sum() but what do you think sum() does behind the scenes? Exactly this!

Here’s another. Let’s say we wanted to calculate the sum of the squares of a list of numbers (which is common enough). Here’s the summation notation (again using zero indexing):

\begin{equation*} \sum\limits^{N-1}_{i = 0} x_i^2 \end{equation*}

Here’s the loop in Python:

s = 0
for e in x:
    s = s + e ** 2

See? The connection between summations and loops is straightforward.

Products

The same applies to products. Just as we can sum by adding all the elements in some list or tuple of numerics, we can also take their product by multiplying. For this, instead of the symbol \sum, we use the symbol \Pi (that’s an upper-case \Pi to distinguish it from the constant \pi).

\begin{equation*} \prod\limits^{N-1}_{i = 0} x_i \end{equation*}

This is the same as

\begin{equation*} x_0 \times x_1 \times \ldots \times x_{N-2} \times x_{N-1} \end{equation*}

The corresponding loop in Python:

p = 1
for e in x:
    p = p * e

Why do we initialize the accumulator to 1? Because that’s the multiplicative identity. If we set this equal to zero the product would be zero, because anything multiplied by zero is zero. Anything multiplied by one is itself. Thus, if calculating a repeated product, we initialize the accumulator to one.

Original author: Clayton Cafiero < [given name] DOT [surname] AT uvm DOT edu >

No generative AI was used in producing this material. This was written the old-fashioned way.

This material is for free use under either the GNU Free Documentation License or the Creative Commons Attribution-ShareAlike 3.0 United States License (take your pick).

Footnotes

  1. Why do we use the trailing underscore? To avoid overwriting the Python built-in function sum() with a new definition.↩︎