[Tutor] Summing a list of numbers / writing small functions

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Fri Apr 11 14:07:01 2003


> > How can I simplify this lines:
> >     > sum = 0
> >     > myList = [1,2,3,4,5,6]
> >     > for each in myList:
> >     >    sum += each
> >
> > Into shorter, more elegant line(s)?
>
> Although Albert has shown you how to do this with reduce() I don't
> actually think there is any need to shorten or make this more elegant.
>
> compare
> sum = reduce(operator.add, myList)
> with
> for x in myList: sum += x
>
> which is shorter? which is more elegant?


Hello!

I think both ways work perfectly well.  The important thing, though, is to
see if we do this summation frequently.  If so, it's probably worth it to
define a add_all() function to capture that idea of adding up elements in
a list.


We've seen two ways of doing it:


###
def add_all(myList):
    sum = 0
    for x in myList:
        sum += x
    return sum
###

and


###
def add_all(myList):
    return reduce(operator.add, myList)
###


As soon as we have some sort of definition for summation --- as soon as we
give it a name --- we can use it as part of our language!


###
>>> add_all(range(10))
45
>>> add_all([2, 4, 6, 8]) + add_all([1, 3, 5, 7, 9])
45
###

add_all(), then, is a very elegant way of doing summations.  *grin*


Hope this helps!