How do I calculate a mean with python?

Steven D'Aprano steve+comp.lang.python at pearwood.info
Mon Sep 16 19:55:07 EDT 2013


On Mon, 16 Sep 2013 16:33:35 -0700, William Bryant wrote:

> Hey I am new to python so go easy, but I wanted to know how to make a
> program that calculates the maen.
> 
> List = [15, 6, 6, 7, 8, 9, 40]
> def mean():
>     global themean, thesum
>     for i in List:
>         thecount = List.count(i)
>         thesum = sum(List)
>     themean = thesum / thecount
> 
> Why doesn't this work?

Let me start by saying that the above is not "best practice" for how to 
write functions, and I'll explain why later, but for now I'll just fix 
the problem with the calculation.

You have List = [15, 6, 6, 7, 8, 9, 40] and then the mean function walks 
through each of the items 15, 6, 6, 7, ... counting how many times that 
item is found:

for i in List:
    thecount = List.count(i)
    thesum = sum(List)


So the first time, i gets the value 15, thecount calculates 
List.count(15) which is 1, thesum calculates sum(List) which is 91, and 
the end of the loop is reached.

The second time around, i gets the value 6, then thecount calculates 
List.count(6) which is 2, thesum calculates sum(List) *again*, which is 
still 91, and the end of the loop is reached.

Third time around, i gets the value 6 again, thecount again gets the 
value 2, thesum yet again sums up List which still hasn't changed, so yet 
again gets 91.

And so on, and so on, until the last iteration, where i gets the value 
40, thecount calculates List.count(40) which is 1, thesum re-calculates 
the sum yet again, still getting the exact same result 91, and finally 
the for-loop comes to an end.

Now the final calculation occurs:

themean = thesum/thecount

which is 91/1 or just 91.

What do you actually want? It's much simpler: you want to count the 
*total* number of items, 7, not by counting each item individually. The 
total number of items is given by the length of the list:

len(List)

returns 7. And you want to sum the list once, there's no need to sum it 7 
times. So the first step is to get rid of the for-loop, just calculate 
thesum = sum(List) once, and thecount = len(List) once.

Once you've done that, please write back with your new code, because I 
think there will be some more improvements to be made.



-- 
Steven



More information about the Python-list mailing list