# sum up numbers in a list

5 messages
Open this post in threaded view
|

## sum up numbers in a list

 hi all,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. all i can think of is check the length of the list (in the above example, 3), then L[0]+L[1]+L[2] ......is there a better way to do the job? thanks. -- http://mail.python.org/mailman/listinfo/python-list
Open this post in threaded view
|

## Re: sum up numbers in a list

 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)) -- http://mail.python.org/mailman/listinfo/python-list
Open this post in threaded view
|

## Re: sum up numbers in a list

 In reply to this post by sharon k  >>> L=['10','15','20']  >>> sum(int(x) for x in L) 45 or  >>> sum(map(int,L)) 45 sharon kim wrote: > hi all, > > 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. > > all i can think of is check the length of the list (in the above > example, 3), then L[0]+L[1]+L[2] ...... > > is there a better way to do the job? thanks. -- http://mail.python.org/mailman/listinfo/python-list