Intermediate·8 min·intermediate · iteration
Generators
Generators
A generator function uses yield. Each yield pauses the function and hands a value to the caller. The next iteration resumes right where it left off.
Why it matters
- Memory: process a billion items without holding them all
- Composition: pipelines of
yieldare tiny and readable
Generator expression
(expr for x in seq) — like a list comprehension but lazy.
Try it
- Write a generator that yields the first
nsquare numbers. - Use a generator expression with
max(...)to find the longest word in a list.