How can I find the mean of a list in Python?

How can I find the mean of a list in Python?

I want to calculate the arithmetic mean of a list in Python. For example, given the list:


[1, 2, 3, 4] ⟶ 2.5

How can I achieve this using mean of list python?

You can calculate the mean by summing the elements of the list and dividing by the number of elements.

def mean_of_list(lst):
    return sum(lst) / len(lst)

# Example usage:
lst = [1, 2, 3, 4]
print(mean_of_list(lst))  # Output: 2.5

The statistics module provides a built-in function mean() to compute the mean of a list.

import statistics

def mean_of_list(lst):
    return statistics.mean(lst)

# Example usage:
lst = [1, 2, 3, 4]
print(mean_of_list(lst))  # Output: 2.5

If you’re working with large datasets or need more advanced numerical operations, you can use the NumPy library, which offers the mean() function.

import numpy as np

def mean_of_list(lst):
    return np.mean(lst)

# Example usage:
lst = [1, 2, 3, 4]
print(mean_of_list(lst))  # Output: 2.5