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.
Python code
27 linesdef 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
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
- Use a list comprehension: `[n * factor for n in data]` instead of a loop.
- 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
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.