Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 9.2 — Generators and yield
Python · Example 1 of 3

Watching a generator pause and resume

The lines in brackets come from inside the generator. Notice that creating the generator prints nothing, and each next() runs only up to the next yield.

A generator function uses yield to hand back values one at a time and freezes in place between them. It writes an iterator in a few lines, keeps its own state, and can produce infinite streams without using memory.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write a generator squares(n) that yields the squares of 1 up to n. Print list(squares(5)).

02

Write a generator countdown(n) that yields n, n-1, ... down to 1, then the text "liftoff". Print each value on its own line with a for loop.

03

Write a generator chunks_of_text(text, size) that yields the text in pieces of at most size characters, then print the pieces for "streaming" with size 4.

Explain it without notes

01

What happens when you call a generator function, and when does its body actually run?

02

How does a generator keep its state between values, and how is that different from an iterator class?

03

What is yield from for, and what does it do that a loop with yield does not?

04

Why can a generator describe an infinite sequence, and how do you use one safely?

05

What do return, raise StopIteration, close() and throw() each do inside or to a generator?

Watching a generator pause and resume
Sign in to run this example in your browser.

Expected output

created the generator, nothing has run yet
  (start)
  (about to yield 1)
got 1
  (resumed after 1)
  (about to yield 2)
got 2
  (resumed after 2)
  (finished)
StopIteration: the generator is done