Finding the average of a list


Question

I have to find the average of a list in Python. This is my code so far

l = [15, 18, 2, 36, 12, 78, 5, 6, 9]
print reduce(lambda x, y: x + y, l)

I've got it so it adds together the values in the list, but I don't know how to make it divide into them?

1
416
1/27/2012 9:15:16 PM

Accepted Answer

If your reduce is already returning your sum, then all you have left to do is divide.

l = [15, 18, 2, 36, 12, 78, 5, 6, 9]
print reduce(lambda x, y: x + y, l) / len(l)

though sum(l)/len(l) would be simpler, as you wouldn't need a lambda.

If you want a more exact float result instead of an int then just use float(len(l)) instead of len(l).

487
1/27/2012 9:00:36 PM

l = [15, 18, 2, 36, 12, 78, 5, 6, 9]
sum(l) / float(len(l))

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon