How to find the average of a list with Python?

Estimated read time 1 min read

To find the average of a list of numbers in Python, you can use the built-in sum() and len() functions. Here’s a simple example:

def find_average(numbers):
    total = sum(numbers)
    count = len(numbers)
    average = total / count
    return average

# Example usage
my_list = [2, 4, 6, 8, 10]
result = find_average(my_list)
print("Average:", result)

In this example, the find_average() function takes a list of numbers as input. It calculates the sum of the numbers using the sum() function and the length of the list using the len() function. Then, it divides the sum by the count to find the average.

In the example usage, the list my_list contains the numbers [2, 4, 6, 8, 10]. The average is calculated as (2 + 4 + 6 + 8 + 10) / 5 = 6.0, and the result is printed as “Average: 6.0”.

Keep in mind that the sum() function assumes the list contains numeric values. If the list contains non-numeric elements, you may encounter an error. If needed, you can add additional validation or error handling in your code to handle such cases.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply