How to Summarize a List of Numbers in Python
Loop over a list of numbers to compute total, count, average, min, and max, then return them in a dictionary.
Python code
29 linesdef summarize_numbers(numbers):
"""Return a dict with basic stats for a list of numbers."""
total = 0
count = 0
smallest = numbers[0]
largest = numbers[0]
for num in numbers:
total += num
count += 1
if num < smallest:
smallest = num
if num > largest:
largest = num
average = total / count
return {
"total": total,
"count": count,
"average": round(average, 2),
"smallest": smallest,
"largest": largest,
}
if __name__ == "__main__":
sample_data = [15, 8, 23, 4, 42, 16]
result = summarize_numbers(sample_data)
print(result)
Output
{'total': 108, 'count': 6, 'average': 18.0, 'smallest': 4, 'largest': 42}
How it works
The function initializes smallest and largest with the first element so the comparisons inside the loop always work. Each iteration adds to total and increments count, updating the min and max as needed. After the loop, the average is calculated by dividing the total by the count, then rounded to two decimal places. Returning a dictionary keeps the computed stats together in a single, easy-to-read structure.
Common mistakes
- Forgetting to handle an empty list, which would cause an IndexError on `numbers[0]`
- Using `sum()` and `len()` without accounting for an empty list division by zero
- Rounding the average at the wrong time, losing precision before further calculations
Variations
- Use built-in functions like `sum(numbers)`, `len(numbers)`, `min(numbers)`, and `max(numbers)` for shorter code
- Use the `statistics` module's `mean()` for more statistical context
Real-world use cases
- Generating summary metrics for a batch of sensor readings in an IoT dashboard.
- Producing quick statistics for user-generated data like daily step counts in a fitness app.
- Preparing descriptive stats for a CSV column before plotting or reporting in a data analysis script.
Sponsored
More from Lists & loops
- Check if List is Sorted Ascending in Python easy
- Compare Two Lists in Python: Common, Only in First, Only in Second easy
- Convert a List of Integers to a Comma-Separated String in Python easy
- Enumerate a Python List with a Custom Start Index easy
- Extract Data by Type from a List in Python: Numbers and Strings easy
- Find All Occurrences of an Item in a Python List easy
Keep learning
Related tutorials and quizzes for this topic.