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.

Easy Python 3.9+ Aug 9, 2026 Comprehensions & generators 14 views 0 copies

Python code

6 lines
Python 3.9+
def 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

stdout
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

  1. Use a list comprehension: `sum([x*x for x in range(1, n+1)])` (less memory-efficient).
  2. 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

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.