[Tutor] Maths operations on lists

Alan Gauld alan.gauld@blueyonder.co.uk
Tue Jun 10 18:58:07 2003


> I *think* what I am after is a way of adding the contents 
> of a list and then dividing that total to yield an average 

You can do that using the list manipulation functions.
One example would be:

import operator
average = reduce(operator.add, myList)/len(myList)

reduce goes thru the list repeatedly combining the first 
two members using the supplied function(add in our case)
until there is only a single value left.

[ For more on reduce and it's cousins see the "Functional 
  Programming" topic in my tutor. ]

We then divide by the length of the list to get the average.

Is that what you mean?

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld