📜  list mean python(1)

📅  最后修改于: 2023-12-03 14:44:01.011000             🧑  作者: Mango

List Mean in Python

In Python, a list is a collection of ordered, mutable values. A list can be defined by enclosing a comma-separated sequence of values in square brackets. The mean of a list is the average value of all the elements in the list.

Calculating the Mean of a List

To calculate the mean of a list in Python, we can use the built-in sum() and len() functions. Here is an example:

my_list = [1, 2, 3, 4, 5]
mean = sum(my_list) / len(my_list)
print(mean)

This code creates a list of integers from 1 to 5 and then calculates the mean of the list by summing up all the elements of the list using sum(my_list) and dividing the total by the number of elements in the list using len(my_list). The resulting mean value is then printed to the console.

Handling Empty Lists

If the list is empty, we need to guard against a ZeroDivisionError that would occur due to dividing by zero. Here's how we can do that:

my_list = []
if not my_list:
    mean = 0
else:
    mean = sum(my_list) / len(my_list)
print(mean)

This code first checks if the list is empty using the not operator and then sets the mean value to zero if the list is empty. Otherwise, it calculates the mean in the same way as before.

Conclusion

In this article, we learned how to calculate the mean of a list in Python using the sum() and len() functions. We also saw how to handle the case of an empty list to avoid a ZeroDivisionError. With this knowledge, you can easily calculate the mean of any list in your Python programs.