How to Find Average of List in Python Quickly and Easily
To find the average of a list in Python, use the
sum() function to add all elements and divide by the number of elements using len(). For example, average = sum(my_list) / len(my_list) calculates the average value.Syntax
The basic syntax to find the average of a list my_list is:
sum(my_list): Adds all numbers in the list.len(my_list): Counts how many numbers are in the list.- Divide the total sum by the count to get the average.
python
average = sum(my_list) / len(my_list)
Example
This example shows how to find the average of a list of numbers and print the result.
python
my_list = [10, 20, 30, 40, 50] average = sum(my_list) / len(my_list) print("Average:", average)
Output
Average: 30.0
Common Pitfalls
Common mistakes when finding averages include:
- Dividing by zero if the list is empty, which causes an error.
- Using integer division in Python 2 (not common now) which truncates decimals.
- Including non-numeric values in the list, which causes
sum()to fail.
Always check the list is not empty and contains only numbers before calculating.
python
my_list = [] # Wrong: This will cause ZeroDivisionError # average = sum(my_list) / len(my_list) # Right: Check list is not empty first if my_list: average = sum(my_list) / len(my_list) print("Average:", average) else: print("List is empty, cannot compute average.")
Output
List is empty, cannot compute average.
Quick Reference
| Operation | Description | Example |
|---|---|---|
| sum(my_list) | Adds all numbers in the list | sum([1, 2, 3]) → 6 |
| len(my_list) | Counts how many items are in the list | len([1, 2, 3]) → 3 |
| Calculate average | Divide sum by length | sum(my_list) / len(my_list) |
Key Takeaways
Use sum() to add list elements and len() to count them for average calculation.
Always check the list is not empty before dividing to avoid errors.
Ensure the list contains only numbers to prevent calculation failures.
The average is a float value representing the central value of the list.