How to Calculate Average in Python
![](https://www.thetechedvocate.org/wp-content/uploads/2023/10/maxresdefault-2023-10-15T202033.677-660x400.jpg)
Introduction
Calculating the average is a common task that is often required when analyzing data or presenting results. In Python, calculating the average can be done easily using a few simple steps. In this article, we will explore different ways to calculate an average in Python.
Method 1: Using the Built-in ‘sum’ and ‘len’ Functions
One of the simplest ways to calculate the average of a list of numbers in Python is by using the built-in ‘sum’ and ‘len’ functions.
Here’s an example:
“`python
numbers = [1, 2, 3, 4, 5]
average = sum(numbers) / len(numbers)
print(“The average is:”, average)
“`
In this example, we have a list of numbers called ‘numbers’. We use the ‘sum’ function to find the total sum of all values in the list and divide it by the length of the list using the ‘len’ function. The result is stored in the variable ‘average’ which we then print to display the calculated average.
Method 2: Using a Custom Function
If you need to calculate averages more frequently or require additional functionality, it may be useful to create a custom function.
Here’s an example of creating and using a custom function for calculating averages:
“`python
def calculate_average(numbers):
total = sum(numbers)
count = len(numbers)
return total / count
numbers = [1, 2, 3, 4, 5]
average = calculate_average(numbers)
print(“The average is:”, average)
“`
In this example, we define a custom function called ‘calculate_average’ which accepts an argument called ‘numbers’. The function calculates the sum and count of elements in the list and returns their quotient as the result. We then call this function passing our list of numbers as an argument and store the returned average in a variable, which we subsequently print.
Method 3: Using the ‘statistics’ Module
Python has a built-in statistics module which provides several statistical functions, including one to calculate the average. To use this module, you need to import it first.
Here’s an example:
“`python
import statistics
numbers = [1, 2, 3, 4, 5]
average = statistics.mean(numbers)
print(“The average is:”, average)
“`
In this example, we first import the ‘statistics’ module. Then, we use the ‘mean’ function from the ‘statistics’ module to calculate the average of our list of numbers. The result is stored in a variable and printed.
Conclusion
Calculating an average in Python can be done in various ways ranging from using simple built-in functions like ‘sum’ and ‘len’, creating custom functions or utilizing the ‘statistics’ module. Depending on your needs and preferences, you can choose any of these methods for calculating averages in Python.