02.03

Generators and iterators

skillmaxingPython with AIGenerators and iterators
Visual lesson

Generators and iterators

Included with Pro · 4:16
Lessons · 1,000 words

Every for loop in Python asks the same two questions. "Give me an iterator" (iter(x)), and then, repeatedly, "give me the next value" (next(it)) until the iterator raises StopIteration. Lists, dicts, files and database cursors all answer those questions, which is why one loop syntax works on all of them. Anything that answers them is an iterable, and you can write your own.

What a for loop actually does
Figure 1What a for loop actually doesAsk for an iterator, then ask it for the next value until it says it is done.

The cheapest way to write one is a generator: a function that contains yield. Calling it runs nothing. It hands back a generator object, and each next() runs the body up to the next yield, pauses there with all its local variables intact, and returns the value. The function's state lives between calls. That pause is the whole trick, and it is why a generator can walk a table of ten million rows while holding one row in memory.

Pro

Continue reading

Pro unlocks every video lesson, the full notes and runnable code across the Python with AI course, from the language itself to agents, MCP, Langfuse and deployment.

Unlock full access to
Python with AIAI researchComplete system design
30% off with LAUNCH30ends in 7h 40m
Buy now
View all plans ·Already Pro? Sign in
124 online