A generator is the easy way to create an iterator: write a normal function but use yield instead of return. Each yield produces a value and pauses the function, resuming from that exact point on the next request. Values are computed lazily, one at a time.
yield pauses and resumes
def squares(n):for i in range(n):yield i * i # produce a value, then freeze heregen = squares(5)next(gen) # 0 — runs until the first yieldnext(gen) # 1 — resumes, runs to the next yieldfor s in squares(5):print(s) # 0 1 4 9 16 — the usual way to consume it
Why it matters: memory & infinity
A generator holds only the current value, so it handles huge or even infinite streams that would never fit in a list:
# Sum a billion squares without building a billion-item listtotal = sum(x * x for x in range(1_000_000_000))def naturals(): # an INFINITE generatorn = 1while True:yield nn += 1# Take just what you need — it never tries to build the whole thing
Generator expressions
Like a comprehension but with parentheses — lazy instead of building a list. Ideal as an argument to sum, any, max:
squares = (n * n for n in range(1000)) # lazy — nothing computed yetany(x > 100 for x in data) # stops at the first match
Key takeaways
- 01A generator function uses yield to produce values lazily, pausing between them.
- 02It holds only the current value in memory — great for huge or infinite streams.
- 03next() drives it manually; a for loop is the usual way to consume it.
- 04Generator expressions (expr for …) are the lazy cousin of comprehensions.
- 05Use generators for large/one-pass/unbounded data; lists for small, reusable, indexable data.
