Input : [4, 5, 1, 2, 9, 7, 10, 8]
Output : Average of the list = 5.75
Explanation:
Sum of the elements is 4+5+1+2+9+7+10+8 = 46
and total number of elements is 8.
So average is 46 / 8 = 5.75
Input : [15, 9, 55, 41, 35, 20, 62, 49]
Output : Average of the list = 35.75
Explanation:
Sum of the elements is 15+9+55+41+35+20+62+49 = 286
and total number of elements is 8.
So average is 46 / 8 = 35.75
sum() : Using sum() function we can get the sum of the list.
len() : len() function is used to get the length or the number of elements in a list.
Python3
# Python program to get average of a list
defAverage(lst):
returnsum(lst) /len(lst)
# Driver Code
lst =[15, 9, 55, 41, 35, 20, 62, 49]
average =Average(lst)
# Printing average of the list
print("Average of the list =", round(average, 2))
Output:
Average of the list = 35.75
Using reduce() and lambda
We can use the reduce() to reduce the loop and by using the lambda function can compute summation of list. We use len() to calculate length as discussed above.
Python3
# Python program to get average of a list
# Using reduce() and lambda
# importing reduce()
fromfunctools importreduce
defAverage(lst):
returnreduce(lambdaa, b: a +b, lst) /len(lst)
# Driver Code
lst =[15, 9, 55, 41, 35, 20, 62, 49]
average =Average(lst)
# Printing average of the list
print("Average of the list =", round(average, 2))
Output:
Average of the list = 35.75
Using mean()
The inbuilt function mean() can be used to calculate the mean( average ) of the list.
Python3
# Python program to get average of a list
# Using mean()
# importing mean()
fromstatistics importmean
defAverage(lst):
returnmean(lst)
# Driver Code
lst =[15, 9, 55, 41, 35, 20, 62, 49]
average =Average(lst)
# Printing average of the list
print("Average of the list =", round(average, 2))
Output:
Average of the list = 35.75
By iterating list
Iterating list using for loop and doing operations on each element of list.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy