list mean
The Python Average function is used to find the average of given numbers in a list.
It can be done in many ways listed below,
- Python Average by using the loop
- By using
sum()
andlen()
built-in average function in Python- Using
mean()
from numpy library- Using
mean()
from the statistics module.
python average
Using For loop
- The for loop will loop through the elements , and each number is added in the
sum
variable. - Then the average of list Python is calculated by using
sum
divided by the count of the numbers in the list usinglen()
built-in function.
def calculateAverage(num): sum = 0 for each in num: sum = sum + each avg = sum / len(num) return avg
Output
print("The average is", calculateAverage([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])) # The average is 5.5
Using sum() and len()
- Here,
sum()
andlen()
built-in functions are used to find average in Python. - It is also the way to calculate the average as you don’t have to loop through the elements.
numList = [11, 12, 13, 14, 15, 16, 17, 18, 19, 20 ]; avg = sum(numList) / len(numList) print("The average is ", avg)
Output
The average is 15.5
Using mean() from numpy
mean()
function that will give us the average for the list.- It is the library is commonly used library to work on large multi-dimensional arrays.
from numpy import mean numList = [21, 22, 23, 24, 25, 26, 27, 28, 29, 30 ]; avg = mean(numList) print("The average is ", avg)
Output
The average is 25.5
Using mean from statistics
- Here , We will using the
mean()
function from the statistics module. mean()
function to calculate the average from the statistics module.
from statistics import mean numList = [31, 32, 33, 34, 35, 36, 37, 38, 39, 40 ]; avg = mean(numList) print("The average is ", avg)
Output
The average is 35.5