February 8, 2025

Average of List in Python

Calculating the average (or mean) of a list of numbers is a common task in Python. The average is computed by summing all the elements in the list and then dividing by the number of elements. Here are several methods to compute the average of a list in Python:

1. Using Built-in Functions

The simplest way to calculate the average is to use the built-in sum() function combined with len():

# Calculate average using built-in functions
def average(lst):
    return sum(lst) / len(lst) if lst else 0

# Example usage
numbers = [10, 20, 30, 40, 50]
avg = average(numbers)
print(avg)  # Output: 30.0
    

2. Using NumPy Library

For large datasets or numerical computations, the numpy library provides efficient methods to compute the average:

import numpy as np

# Calculate average using NumPy
def average_np(lst):
    return np.mean(lst)

# Example usage
numbers = [10, 20, 30, 40, 50]
avg = average_np(numbers)
print(avg)  # Output: 30.0
    

3. Using a Loop

For educational purposes or when avoiding external libraries, you can manually compute the average using a loop:

# Calculate average using a loop
def average_loop(lst):
    total = 0
    count = 0
    for num in lst:
        total += num
        count += 1
    return total / count if count != 0 else 0

# Example usage
numbers = [10, 20, 30, 40, 50]
avg = average_loop(numbers)
print(avg)  # Output: 30.0
    

4. Using List Comprehension

While less common, list comprehension can be used to compute the average, particularly for applying transformations:

# Calculate average using list comprehension
def average_comprehension(lst):
    return sum([num for num in lst]) / len(lst) if lst else 0

# Example usage
numbers = [10, 20, 30, 40, 50]
avg = average_comprehension(numbers)
print(avg)  # Output: 30.0
    

5. Conclusion

There are various ways to calculate the average of a list in Python. The method you choose depends on your specific needs, such as performance considerations or library usage. For basic tasks, built-in functions are sufficient, while libraries like NumPy offer more advanced capabilities for numerical computations.