When a function must produce values one at a time instead of building a complete list, yield turns it into a generator function. Calling it returns a generator object; iteration runs until yield produces a value, then suspends execution until the next value is requested. section 10.0
A generator using yield behaves as follows:
- Calling the function creates a generator object without immediately executing its body. section 10.0
- Each next request resumes execution at the suspended point and continues through the next yield. section 10.0
- Reaching the end of the generator ends iteration automatically with StopIteration; return exits the generator instead of producing another value. section 10.15
- Local variables retain their values between yields, allowing a generator to remember progress across iterations. section 10.17
A three-value generator
def foo(): yield 1 yield 2 yield 3 g = foo() for value in g: print(value) The loop prints 1, 2, and 3. Each iteration advances g to the next yield, while the function keeps its position between iterations. section 10.0
Streaming filtered input
A generator can read a file one line at a time, yield only lines containing a desired string, and pause immediately after each matching line. This avoids collecting all matching lines before the caller can use them. section 10.12
Keeping state between results
A timing generator can calculate the elapsed time since its previous iteration, set last_time before yielding (delta, item), and reuse that retained value on the next request. section 10.17









