Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the average of a list

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

from functools import reduce  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?

like image 747
Carla Dessi Avatar asked Jan 27 '12 20:01

Carla Dessi


People also ask

How do you find the average of a list?

Summary: The formula to calculate average is done by calculating the sum of the numbers in the list divided by the count of numbers in the list.

How do I find the average of a list in Python?

There are two ways to find the average of a list of numbers in Python. You can divide the sum() by the len() of a list of numbers to find the average. Or, you can find the average of a list using the Python mean() function. Finding the average of a set of values is a common task in Python.

Can you average a list in Python?

In Python we can find the average of a list by simply using the sum() and len() function.

How do you print the average of an element in a list Python?

Step 1: input “size of the list” Step 2: input “Element” Step 3: using sum function calculate summation of all numbers. Step 4: calculate average.


2 Answers

On Python 3.8+, with floats, you can use statistics.fmean as it's faster with floats.

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:

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 functools.reduce as it is much slower.

like image 66
Herms Avatar answered Nov 23 '22 23:11

Herms


l = [15, 18, 2, 36, 12, 78, 5, 6, 9] sum(l) / len(l) 
like image 38
yprez Avatar answered Nov 23 '22 23:11

yprez