Sum of Squares with a Generator Expression in Python
This code computes the sum of squares of integers from 1 to n using a generator expression, demonstrating a memory-efficient and concise way to aggregate a sequence.
Python code
6 linesdef sum_of_squares(n):
return sum(x * x for x in range(1, n + 1))
if __name__ == "__main__":
print(f"Sum of squares from 1 to 5: {sum_of_squares(5)}")
print(f"Sum of squares from 1 to 10: {sum_of_squares(10)}")
Output
Sum of squares from 1 to 5: 55
Sum of squares from 1 to 10: 385
How it works
The sum() function takes an iterable and adds up its elements. Here, a generator expression (x * x for x in range(1, n + 1)) yields each square one at a time without building a list, which saves memory for large n. The range object provides the numbers from 1 to n inclusive. This pattern combines lazy evaluation with built-in aggregation for efficient computation.
Common mistakes
- Forgetting parentheses when the generator expression is the only argument; `sum(x*x for x in ...)` works, but `sum(x*x for x in ..., start)` may need them.
- Using a list comprehension instead, which creates an entire list and uses more memory.
- Off-by-one errors with `range(1, n)` instead of `range(1, n+1)`.
Variations
- Use a list comprehension: `sum([x*x for x in range(1, n+1)])` (less memory-efficient).
- Use the formula `n*(n+1)*(2*n+1)//6` for an O(1) solution.
Real-world use cases
- Calculating total energy consumption from a list of per-device power usage squares when aggregating metrics.
- Computing the sum of squared errors in a data analysis script without storing large intermediate lists.
- Summing squares of feature values in a streaming or generator-based data pipeline.
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.