[Tutor] Getting total of a list (newbie)

Ignacio Vazquez-Abrams ignacio@openservices.net
Tue, 11 Sep 2001 09:56:56 -0400 (EDT)


On Tue, 11 Sep 2001 Brmfq@aol.com wrote:

> I'm running Python 1.5.2 on win16 (going to upgrade both soon). I've been
> working on an exercise of writing a program that reads 100 numbers from the
> user and prints out the sum. Here's the best I've come up with:
>
> num = input("Please enter a number:")
> tot = [num]
> while len(tot) < 10:
>      nex = input("Please enter another number: ")
>      tot.append (nex)
> print 'total of 10 numbers is',
> tot[0]+tot[1]+tot[2]+tot[3]+tot[4]+tot[5]+tot[6]+tot[7]+tot[8]+tot[9]
>
> This works, but it's only for 10 numbers. Could someone please show me a
> better way? Thanks in advance to anyone who replies.

This works for an arbitrary list or tuple of numbers:

---
import operator

print reduce(operator.add, tot)
---

-- 
Ignacio Vazquez-Abrams  <ignacio@openservices.net>