How to summarize and transform lists in Python

Compute count, sum, min, max, and average for a list and multiply each element by a factor using simple loops and built-in functions.

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

Python code

27 lines
Python 3.9+
def summarize(data):
    """Return a summary of a list: count, sum, min, max, average."""
    count = len(data)
    total = sum(data)
    minimum = min(data)
    maximum = max(data)
    average = total / count if count else 0
    return count, total, minimum, maximum, average


def multiply_elements(data, factor=2):
    """Return a new list with each element multiplied by factor."""
    result = []
    for number in data:
        result.append(number * factor)
    return result


if __name__ == "__main__":
    numbers = [3, 7, 2, 9, 5]
    count, total, minimum, maximum, average = summarize(numbers)
    print(f"Count: {count}")
    print(f"Sum: {total}")
    print(f"Min: {minimum}")
    print(f"Max: {maximum}")
    print(f"Average: {average}")
    print(f"Doubled: {multiply_elements(numbers)}")

Output

stdout
Count: 5
Sum: 26
Min: 2
Max: 9
Average: 5.2
Doubled: [6, 14, 4, 18, 10]

How it works

The summarize function uses Python's built-in len, sum, min, and max to gather statistics, then computes the average with a ternary to avoid division by zero on empty lists. multiply_elements builds a new list by looping over the input, appending each element times the factor, which preserves the original list. Returning a tuple from summarize lets callers unpack multiple values directly. The if __name__ guard makes the demo run only when the script is executed, keeping it importable elsewhere.

Common mistakes

  • Dividing by zero when the list is empty — use a guard like `total / count if count else 0`.
  • Assuming `sum`, `min`, or `max` handle empty lists — they raise `ValueError`.
  • Mutating the original list in place when you meant to return a new one.

Variations

  1. Use a list comprehension: `[n * factor for n in data]` instead of a loop.
  2. Use `statistics.mean(data)` from the stdlib for the average.

Real-world use cases

  • Generating performance metrics like average response time and peak load from numeric logs.
  • Scaling sensor readings or price arrays by a constant factor before storing or plotting.
  • Producing quick dashboard stats — total sales, min/max order value, average order size.

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.