L5Β·Intermediate/Advanced
πIterators & Generators
Lazy sequences you can walk once.
iternextyieldgenerator
Β§ 1Iterator protocol
An iterator has __iter__ returning self and __next__ raising StopIteration when done.
Β§ 2Generators
def with yield produces a generator function β each yield suspends state until next() resumes.
Β§ 3yield from
Delegates iteration to a sub-iterable β flattens nested generators.
Animated step-through
step 1 / 6// fib(10) creates a generator (no code runs yet)
1def fib(n):β2 a, b = 0, 1β3 for _ in range(n):β4 yield aβ5 a, b = b, a + bβ6β7print(list(fib(10)))βVariables
β none yet β
Try it live Β· Python runs in your browser
Loading playgroundβ¦
Checkpoint quiz
Question 1 / 2
What does calling a generator function do?