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.

Worked example

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)))​

Try it live · Python runs in your browser

Loading playground…

Checkpoint quiz

Question 1 / 2
What does calling a generator function do?

Lesson test

Take an 8-question test on “Iterators & Generators” — concepts, output prediction, bug spotting and interview questions.