Introduction to generators and yield
You already know how to build a list inside a function and return it. Generators are functions that hand back values one at a time, on demand, using yield. This lesson shows what changes when you swap return for yield.
So far, when a function had to return many values, you built a list inside the function and returned the whole thing.
Here is a function that returns the first three squares as a list:
That works for three values. But imagine the function had to produce a million. The full list would sit in memory all at once, even if the caller only needs the values one at a time.
Generators solve this. They produce values on demand, one by one, without ever building the full collection. The keyword is yield.
Any function that contains yield is a generator function:
The squares example, rewritten as a generator:
Each yield pauses the function. The next request picks up where it left off, with all the local state intact:
What will be the output?
Calling a generator function does not run it. It returns a generator object:
Use next() to ask the generator for one value at a time:
This is where generators pay off. The loop below would build a list of a billion numbers and crash on memory. The generator version pulls just the first three and stops, never computing the rest:
Pass the generator to list() to collect every value at once:
What will be the output?
What will be the output?
What will be the output?
What will be the output?