Log inStart free
LESSON 1.05 · 6 STAGES · 2 CONTROLS · 3 CHECKSPRO · PREVIEW

Iterators and generators

Watch a generator pause at yield, keep its local names, and resume on next().


Pro lesson. Stage 1 is free to watch. Pro opens all 6 stages, 2 controls and 3 checks, in this lesson and every other.

Go Pro · $8.25/mo
EXPLAINER · 1.05 · ITERATOR BAYGEN_CREATED AT LINE 1 · 0 PRINTED
01
Stage 1 of 6 · Make an iterator
Calling countdown(2) runs no line of its body. The call makes a generator whose frame has not started.
Explain it simply

Calling countdown doesn't run its code yet. Python makes a generator, an object that holds a frame for later. A frame is the record of one call, with its local names. Look inside: n is already 2, but the mark on line 1 says not started.

The name it points to a generator with id 2176. The generator's frame has not started: line 1, with n equal to 2.

name, frameobject, valuereference, saved placerunning line, value handed outStopIteration, used up
programcall stackobjects1def countdown(n):2 while n > 0:3 yield n4 n -= 16it = countdown(2)7for x in it:8 print(x)9for x in it:10 print(x)not startedprintedloop 1loop 2generator · id 2176GEN_CREATEDfunction · id 2128countdown(n)2<module>line 6itcountdowncountdown(2)line 1nprogramcall stackobjects1def countdown(n):2 while n > 0:3 yield n4 n -= 16it = countdown(2)7for x in it:8 print(x)9for x in it:10 print(x)not startedprintedloop 1loop 2generator · id 2176GEN_CREATEDfunction · id 2128countdown(n)2<module>line 6itcountdowncountdown(2)line 1n
Toy: countdown(2) or iter([2, 1]) · CPython 3.12 · ids are stand-ins
STAGE 1 / 6
MATH · STAGE 1HOVER A SYMBOL OR A SHAPE
state(it)=saved place\mathrm{state}(\sy{it}{data}{\mathit{it}}) = \sy{pos}{param}{\text{saved place}}
state(it)=(line 1, n=2), 0 lines run\mathrm{state}(\mathit{it}) = (\text{line } 1,\ n = 2),\ \text{0 lines run}

An iterator keeps only the state that the next value needs.

Common mix-ups

MYTHCalling a generator function runs its body.

The fix, and 1 more mix-up with the diagram to show them, come with Pro.

Predict, then reveal
3 CHECKS · PRO
Q01With a list iterator, what keeps the place between next() calls?

Make your guess, then test it in the diagram. All 3 checks come with Pro.

PRO LESSON · YOU WATCHED STAGE 1 OF 6
Unlock the full explainer
  • 5 more stages and 2 live controls
  • 2 mix-up cards and 3 predict-then-reveal checks
  • Watch it as a narrated video, in three voices
  • Every Pro lesson and capstone · 656 in total

$99 a year, or $15 a month. Cancel any time.