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.
Python code
13 linesdef 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
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
- 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)`.
- 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
More from Comprehensions & generators
- Batch Rows in Chunks with a Generator in Python easy
- Build a Generator Pipeline in Python: Filter Then Map medium
- Build a lazy generator to read file lines in Python easy
- Chunk an Iterable into Batches with a Generator in Python easy
- Convert Data in Python with Comprehensions and Generators easy
- Count Data in Python with Comprehensions and Generators easy
Keep learning
Related tutorials and quizzes for this topic.