sum up numbers in a list
Fredrik Lundh
fredrik at pythonware.com
Tue Aug 26 13:25:38 EDT 2008
sharon kim wrote:
> i have a list, for example;
>
> >>> L=[]
> >>> L.append('10')
> >>> L.append('15')
> >>> L.append('20')
> >>> len(L)
> 3
> >>> print L
> ['10', '15', '20']
>
> is there a way to sum up all the numbers in a list? the number of
> objects in the list is vary, around 50 to 60. all objects are 1 to 3
> digit positive numbers.
the for-in statement is your friend:
S = 0
for item in L:
S += int(item)
it can also be used in-line (this is called a "generator expression"):
S = sum(int(v) for v in L)
or even hidden inside a built-in helper function:
S = sum(map(int, L))
</F>
More information about the Python-list
mailing list