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/moEXPLAINER · 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
Toy: countdown(2) or iter([2, 1]) · CPython 3.12 · ids are stand-ins
MATH · STAGE 1HOVER A SYMBOL OR A SHAPE
An iterator keeps only the state that the next value needs.
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.