Generators
A normal function returns once and hands back one value. A generator function
uses yield instead of return, and can hand back many values, one at a
time, pausing exactly where it left off between each one. Calling it doesn't
run the body at all yet - it returns a generator object, and the code only
runs as each value is pulled out.
That laziness is the whole point: list(squares(1000000)) on a normal
function builds a million-item list in memory before you get anything back;
a generator hands you the first value immediately and computes the rest only
if you keep asking. list(some_generator()) or a for loop will pull every
value out and collect them, same as any other iterable.
Your task: write a generator function squares(n) that yields the square
of each integer from 1 to n, in order, one at a time, using yield
instead of building and returning a list.
You'll practice:
- Writing a generator function with
yield
- Understanding that calling it returns a lazy generator, not a list
Related reading: Iterators & Generators →