How to Use List Comprehensions and Generators in Python

Analyze a list of numbers using a list comprehension to square evens, a generator for sum, and a generator expression for the maximum squared value.

Easy Python 3.8+ Aug 9, 2026 Comprehensions & generators 11 views 0 copies

Python code

13 lines
Python 3.8+
def analyze_numbers(numbers):
    squared = [n ** 2 for n in numbers if n % 2 == 0]
    total = sum(n for n in numbers)
    max_squared = max((n ** 2 for n in numbers), default=0)
    return squared, total, max_squared


if __name__ == "__main__":
    data = [1, 2, 3, 4, 5, 6]
    evens_squared, total_sum, max_sq = analyze_numbers(data)
    print(f"Evens squared: {evens_squared}")
    print(f"Total sum: {total_sum}")
    print(f"Max squared value: {max_sq}")

Output

stdout
Evens squared: [4, 16, 36]
Total sum: 21
Max squared value: 36

How it works

The list comprehension [n ** 2 for n in numbers if n % 2 == 0] builds a new list by iterating over numbers, filtering even numbers, and squaring each. The generator expression sum(n for n in numbers) passes a generator to sum(), which consumes it lazily without creating an intermediate list. Similarly, max((n ** 2 for n in numbers), default=0) computes the maximum squared value; the default parameter prevents a ValueError if numbers is empty. These constructs are memory-efficient for large collections because generators produce values on the fly.

Common mistakes

  • Forgetting the `default` argument in `max()` or `min()` on an empty generator, causing a ValueError.
  • Using square brackets in `sum()` unnecessarily, building a full list instead of a generator.
  • Misplacing the `if` condition in a list comprehension, filtering the wrong element.

Variations

  1. Use a generator expression for squared evens if you don't need the full list: `(n ** 2 for n in numbers if n % 2 == 0)`.
  2. Replace `sum(n for n in numbers)` with the built-in `sum(numbers)` since `sum` accepts an iterable directly.

Real-world use cases

  • Computing summary statistics like sums and maxima from sensor data streams without loading all values into memory.
  • Transforming and filtering user IDs in a dataset before sending them to an analytics dashboard.
  • Generating squares of even transaction amounts for reporting while keeping the code concise and readable.

Sponsored

Run this sample

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

Open editor

More from Comprehensions & generators

Related tutorials and quizzes for this topic.