[Tutor] simple math but I can't quite get it
Fri, 9 Feb 2001 23:03:19 -0800 (PST)
On Fri, 9 Feb 2001 firstname.lastname@example.org wrote:
> for a list of integers
> how can I get the sum total of all integers in this list?
> I just can't qutie make it on this one :(
Hello! There are several approaches to this.
If we know that 'a' will always contain 5 numbers, we can go with the
sum = a + a + a + a + a
So instead, I'll interpret your question as: "How do I add up any list of
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
There are other ways of adding numbers; one of these ways is the
>>> def add(x, y): return x + y
>>> sum = reduce(add, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
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])
Anyway, hope this helps!