Picture this: yield one item at a time
A generator does not build the whole list. It pauses at yield.
def gen()function
→
yield xpause, send x
→
next(...)resume
→
StopIterationdone
In easy words
A generator remembers where it stopped. Each next(g) continues until the next yield — great when you do not want a huge list in memory.
Where this shows up
Reading large files line-by-line, streaming API pages, infinite sequences with a stop rule.
Key facts
- yield — Pause and send a value
- State — Locals survive between yields
- next(g) — Resume until next yield
- Lazy — Values appear on demand
What to remember
- Practice — squares: 0,1,4,9,16…
- Stop rule — Take first N with a loop
- Vs list — Generators do not store everything
- One-pass — Consuming advances; reset by recreating
next() demo
Generator ready at i=0
1def squares():
2i = 0
3while True:
4yield i * i
5i += 1