⚡ Comprehensions & Iteration, lesson 5 of 5
Generators and lazy iteration
Produce values on demand with generator expressions and yield.
11 min
1 exercise
3 quizzes
0/4 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.
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.
Why write sum(x * x for x in data) instead of sum([x * x for x in data])?