Generator expression of squares

EasyIterator & Generator Programs · 6 of 20

Write a Python program that sums squares with a generator expression.

Advertisement
Output
generator
385
0

Approach

  1. Round brackets create a lazy generator.

Solution

Python
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.

More iterator & generator programs

← All 20 Iterator & Generator Programs

Leave a Comment