[Tutor] Summing a list of numbers / writing small functions
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.
> sum = reduce(operator.add, myList)
> for x in myList: sum += x
> which is shorter? which is more elegant?
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
We've seen two ways of doing it:
sum = 0
for x in myList:
sum += x
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([2, 4, 6, 8]) + add_all([1, 3, 5, 7, 9])
add_all(), then, is a very elegant way of doing summations. *grin*
Hope this helps!