Using Generators with yield
Using Generators with Yield in Python
Writing custom iterator classes requires boilerplate code: tracking indices, defining __iter__(), handling __next__(), and manually managing StopIteration.
Generators provide a simple, elegant way to create iterators using regular functions. By replacing the return statement with yield, Python handles the entire Iterator Protocol automatically behind the scenes.
1. What is yield?
When a function contains the yield keyword, Python automatically compiles it into a Generator Function. Calling this function does not execute its body immediately; instead, it returns a Generator Object.
return: Terminates the function completely and returns a value, destroying its local stack frame.yield: Produces a value, pauses function execution, and preserves its entire execution context (all local variables and instruction pointer) in memory until the next value is requested.
2. Memory Efficiency: Processing Huge Files
The superpower of generators is lazy evaluation—values are computed strictly on-demand.
Consider reading a 10 GB log file. Reading it into a standard list with .readlines() will immediately exhaust system RAM with an OutOfMemory crash. A generator reads one line at a time with near-zero memory footprint:
3. Building Generator Pipelines
You can chain multiple generators together like unix pipes (|) to form clean, modular data processing pipelines:
4. Advanced Generator Features: send() and close()
Generators can also receive data back from the caller via .send(value):
5. Comparison: Regular Function vs. Generator
| Attribute | Regular Function | Generator Function |
|---|---|---|
| Keyword | Uses return | Uses yield |
| Execution | Executes to completion in one call | Pauses and resumes on demand |
| Return Value | Single value or collection | Generator object |
| Memory | Stores entire result set in RAM | Generates values lazily one at a time |
| Protocol | Not iterable by default | Implements Iterator Protocol natively |
Multiple Choice Questions
1. What does Python return when a function containing a yield statement is invoked?
A. The value specified after yield B. A Generator object implementing the Iterator Protocol C. A tuple of all yielded elements D. None Answer: B Explanation: Calling a generator function does not run the code immediately; it returns a generator object that controls execution via next().
2. How does yield differ from return?
A. yield can only return integers, while return returns any object B. yield pauses the function state and preserves its local variables, while return destroys the execution frame C. yield forces Python into multi-threaded mode D. There is no operational difference Answer: B Explanation: yield pauses the function and saves its local state so execution can resume seamlessly upon the next call to next().
3. What exception is automatically raised when a generator function reaches its end or an empty return?
A. GeneratorExit B. StopIteration C. SystemExit D. IndexError Answer: B Explanation: When a generator function finishes executing or hits a return, Python automatically raises StopIteration to signal that the iterator is exhausted.
4. Why are generators essential when parsing massive datasets (such as a 50 GB log file)?
A. They compress data into zip format in memory B. They load only one record at a time into RAM (lazy evaluation), preventing out-of-memory crashes C. They bypass Python's Global Interpreter Lock (GIL) D. They execute in GPU memory Answer: B Explanation: Generators evaluate lazily, consuming minimal constant memory regardless of the total size of the stream being processed.
5. Which generator method allows sending a value back into the generator function at the point of yield?
A. push() B. send() C. insert() D. feed() Answer: B Explanation: The .send(value) method resumes the generator and provides a value that becomes the result of the current yield expression inside the generator.
Generator Expressions
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Custom Iterators | Generator Expressions |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.