Python Practice › Iterator & Generator Programs › Program 6
Generator expression of squares
Write a Python program that sums squares with a generator expression.
Output
generator 385 0
Approach
- Round brackets create a lazy generator.
Solution
squares = (n * n for n in range(1, 11))print(type(squares).__name__)print(sum(squares))print(sum(squares))Output
generator 385 0
Line by line
Line 4
The generator is used up after the first sum, so the second sum is 0.
Learn the concept
New to this topic? Read the lesson, then come back.