Generators and lazy iteration

Comprehensions & Iteration, lesson 5 of 5

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

Example

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.

Example

any() and all()

Change 49 to 55 and run it again.

Quiz

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.

Example

A countdown generator

Add a print before the yield to watch the function pause and resume.

Example

Used up

Change the parentheses to square brackets. Now it's a list you can reuse.

Quiz

What does this print?

Example

Endless, but lazy

An infinite generator is fine as long as you stop asking for values. Never call list() on one!

Exercise

Fibonacci generator

  1. Write a generator function fib(limit) that yields the Fibonacci numbers (0, 1, 1, 2, 3, 5, …) that are less than limit. Each number is the sum of the two before it.
  2. Set even_sum to the sum of the even numbers from fib(100), using a generator expression.
Quiz

Why write sum(x * x for x in data) instead of sum([x * x for x in data])?