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)
as a beginner, I just coded this:
L = [15, 18, 2, 36, 12, 78, 5, 6, 9]
total = 0
def average(numbers):
total = sum(numbers)
total = float(total)
return total / len(numbers)
print average(L)
On Python 3.4+ you can use statistics.mean()
l = [15, 18, 2, 36, 12, 78, 5, 6, 9]
import statistics
statistics.mean(l) # 20.11111111111111
On older versions of Python you can do
sum(l) / len(l)
On Python 2 you need to convert len
to a float to get float division
sum(l) / float(len(l))
There is no need to use reduce
. It is much slower and was removed in Python 3.
Instead of casting to float, you can add 0.0 to the sum:
def avg(l):
return sum(l, 0.0) / len(l)
Combining a couple of the above answers, I've come up with the following which works with reduce and doesn't assume you have L
available inside the reducing function:
from operator import truediv
L = [15, 18, 2, 36, 12, 78, 5, 6, 9]
def sum_and_count(x, y):
try:
return (x[0] + y, x[1] + 1)
except TypeError:
return (x + y, 2)
truediv(*reduce(sum_and_count, L))
# prints
20.11111111111111
Find the average in list By using the following PYTHON code:
l = [15, 18, 2, 36, 12, 78, 5, 6, 9]
print(sum(l)//len(l))
try this it easy.
print reduce(lambda x, y: x + y, l)/(len(l)*1.0)
or like posted previously
sum(l)/(len(l)*1.0)
The 1.0 is to make sure you get a floating point division