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.

Easy Python 3.9+ Aug 9, 2026 Lists & loops 16 views 0 copies

Python code

29 lines
Python 3.9+
def 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

stdout
{'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

  1. Use built-in functions like `sum(numbers)`, `len(numbers)`, `min(numbers)`, and `max(numbers)` for shorter code
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Lists & loops

Related tutorials and quizzes for this topic.