Home >Backend Development >Python Tutorial >How Can I Calculate the Arithmetic Mean of a List in Python Efficiently and Accurately?
Finding the Arithmetic Mean of a List in Python
Calculating the average of a list in Python involves the arithmetic mean, represented as the sum of all values divided by the number of values. Here are various approaches, focusing specifically on numerical stability:
For Python 3.8 and higher, the recommended method is to utilize the statistics.fmean function, which offers improved accuracy for floating-point calculations:
import statistics list_of_numbers = [1, 2, 3, 4] average = statistics.fmean(list_of_numbers) print(average) # Output: 2.5
For Python 3.4 and later, the statistics.mean function can be employed for numerical stability with floats:
import statistics list_of_numbers = [15, 18, 2, 36, 12, 78, 5, 6, 9] average = statistics.mean(list_of_numbers) print(average) # Output: 20.11111111111111
In earlier versions of Python 3, a simple calculation using the sum() and len() functions can be used, ensuring that the division results in a float:
list_of_numbers = [1, 2, 3, 4] average = sum(list_of_numbers) / len(list_of_numbers) print(average) # Output: 2.5
For Python 2, casting the length of the list to a float ensures float division:
list_of_numbers = [1, 2, 3, 4] average = sum(list_of_numbers) / float(len(list_of_numbers)) print(average) # Output: 2.5
The above is the detailed content of How Can I Calculate the Arithmetic Mean of a List in Python Efficiently and Accurately?. For more information, please follow other related articles on the PHP Chinese website!