[Tutor] simple math but I can't quite get it

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Fri, 9 Feb 2001 23:03:19 -0800 (PST)

On Fri, 9 Feb 2001 michaelbaker@operamail.com wrote:

> for a list of integers
> a=[23,45,65,27,98]
> how can I get the sum total of all integers in this list?
> I just can't qutie make it on this one :(
> thanks

Hello!  There are several approaches to this.

If we know that 'a' will always contain 5 numbers, we can go with the
direct route:

    sum = a[0] + a[1] + a[2] + a[3] + a[4]

So instead, I'll interpret your question as: "How do I add up any list of
numbers together?"

One thing we can do keep a running total.  We can look at each number in
turn, and add it to our running total, until we run out of numbers to look
at.  In Python, it looks like this:

    sum = 0
    for x in a:
        sum = sum + x

This is probably one of the simpler, straightforward ways of adding those
numbers up.  Whenever you use lists, you'll probably make a lot of use of
for loops.

There are other ways of adding numbers; one of these ways is the
"functional" approach:

>>> def add(x, y): return x + y
>>> sum = reduce(add, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
>>> sum

This, too, tells Python to: "Reduce all those list elements into a single
thing, by using the add() function repeatedly."  It might be a little
weird because we're feeding the add() function itself into the reduce()
function, but it's not too hard once you play with it.

Here's another example of using reduce to find the product of all numbers
in a list:

>>> def mul(x, y): return x * y
>>> product = reduce(mul, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
>>> product

Anyway, hope this helps!