⚡ Comprehensions & Iteration, lesson 5 of 5
Generators and lazy iteration
Produce values on demand with generator expressions and yield.
11 min
2 exercises
3 quizzes
0/5 solved
Getting Python ready… examples can run in a moment.
Swap the square brackets of a list comprehension for
parentheses and you get a generator expression.
It doesn't build a list; it produces values one at
a time, on demand. That saves memory, and it's
perfect for feeding sum, max, min,
any and all directly.
No list needed
When a generator is the only argument, you can drop its extra parentheses.
any is True if at least one value is true;
all is True only if every value is. Both
stop as soon as they know the answer.
any() and all()
Change 49 to 55 and run it again.
What does this print?
You can also write a generator function with
yield. Each yield hands out one value and
pauses the function; it resumes right there when
the next value is requested.
A countdown generator
Add a print before the yield to watch the function pause and resume.
Pause at yield, resume on next()
gen = countdown(3) runs none of the body yet. It only creates a generator, waiting for someone to ask for a value.
gen = countdown(3), then next(gen) four times
Used up
Change the parentheses to square brackets. Now it's a list you can reuse.
What does this print?
Endless, but lazy
An infinite generator is fine as long as you stop
asking for values. Never call list() on one!
Fibonacci generator
- Write a generator function
fib(limit)that yields the Fibonacci numbers (0, 1, 1, 2, 3, 5, …) that are less thanlimit. Each number is the sum of the two before it. - Set
even_sumto the sum of the even numbers fromfib(100), using a generator expression.
Chunks on demand
Write a generator function chunks(items, size) that
yields consecutive slices of items, each with
size items. The last chunk may be shorter. Yield each
chunk as you go instead of building a list of chunks.
For [1, 2, 3, 4, 5] with size 2, it yields [1, 2],
then [3, 4], then [5].
Why write sum(x * x for x in data) instead of sum([x * x for x in data])?