Python | Average of Float Numbers

While working with Python, we can have a problem in which we need to find mean of a list cumulative with float elements. This problem is common in Data Science domain. Let’s discuss certain ways in which this problem can be solved.

Method #1 : Using loop + formula
The simpler manner to approach this problem is to employ the formula for finding mean and perform using loop shorthands. This is the most basic approach to solve this problem.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of 
# Average of Float Numbers 
# using loop + formula 
import math
  
# initialize list 
test_list = [6.1, 7.2, 3.3, 9.4, 10.6, 15.7
  
# printing original list 
print("The original list is : " + str(test_list)) 
  
# Average of Float Numbers
# using loop + formula 
sum = 0
for ele in test_list:
  sum += ele
res = sum / len(test_list)
  
# printing result 
print("The mean of float list elements is : " + str(res)) 

chevron_right


Output :

The original list is : [6.1, 7.2, 3.3, 9.4, 10.6, 15.7]
The mean of float list elements is : 8.716666666666667

 

Method #2 : Using statistics.fmean()
This task can also be performed using inbuilt function of fmean(). This is new in Python versions >= 3.8.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of 
# Average of Float Numbers
# using statistics.fmean() 
import statistics 
  
# initialize list 
test_list = [6.1, 7.2, 3.3, 9.4, 10.6, 15.7
  
# printing original list 
print("The original list is : " + str(test_list)) 
  
# Average of Float Numbers
# using statistics.fmean() 
res = statistics.fmean(test_list) 
  
# printing result 
print("The mean of float list elements is : " + str(res)) 

chevron_right


Output :

The original list is : [6.1, 7.2, 3.3, 9.4, 10.6, 15.7]
The mean of float list elements is : 8.716666666666667



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.