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.
Python3
import math
test_list = [ 6.1 , 7.2 , 3.3 , 9.4 , 10.6 , 15.7 ]
print ("The original list is : " + str (test_list))
sum = 0
for ele in test_list:
sum + = ele
res = sum / len (test_list)
print ("The mean of float list elements is : " + str (res))
|
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
Time Complexity: O(n) where n is the number of elements in the list “test_list”.
Auxiliary Space: O(n) where n is the number of elements in the list “test_list”.
Method #2 : Using statistics.fmean() This task can also be performed using inbuilt function of fmean(). This is new in Python versions >= 3.8.
Python3
import statistics
test_list = [ 6.1 , 7.2 , 3.3 , 9.4 , 10.6 , 15.7 ]
print ("The original list is : " + str (test_list))
res = statistics.fmean(test_list)
print ("The mean of float list elements is : " + str (res))
|
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
Time Complexity: O(n), where n is the number of elements in the list “test_list”.
Auxiliary Space: O(1), where constant extra space is required
Method #3 : Using numpy.mean()
Note: Install numpy module using command “pip install numpy”
Python3
import numpy as np
test_list = [ 6.1 , 7.2 , 3.3 , 9.4 , 10.6 , 15.7 ]
print ( "The original list is : " + str (test_list))
res = np.mean(test_list)
print ( "The mean of float list elements is : " + str (res))
|
We can use numpy library’s mean function to calculate the mean of a list of floats.
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
Time complexity: O(n) as we are iterating through the list only once.
Auxiliary Space: O(1) as we are not using any extra data structures.
Approach 4: Using a built-in Python function sum() and len()
Python3
import math
test_list = [ 6.1 , 7.2 , 3.3 , 9.4 , 10.6 , 15.7 ]
print ( "The original list is : " + str (test_list))
mean = sum (test_list) / len (test_list)
print ( "The mean of float list elements is : " + str (mean))
|
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
Time complexity: O(n) as we are iterating through the list only once using the sum() function.
Auxiliary Space: O(1) as we are not using any extra data structures.
Last Updated :
09 Apr, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...