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?