Mastering the Yield Statement for State Persistence
In this lesson, you will learn how the yield statement allows a function to "pause" its execution and remember its local variables, enabling you to create custom, memory-efficient data streams.
The Power of Pausing
When you use a return statement in a standard function, the function completes its task and destroys all its local variables. The memory is cleared, and the state is lost. A generator function, however, uses yield. When Python hits yield, it pauses the function, "returns" the requested value to the caller, and—crucially—saves the entire state of the function.
The next time you ask the generator for a value, it resumes exactly where it left off, keeping the local variables exactly as they were.
A Practical Illustration
Imagine you need a function that counts up but keeps track of a "running total" or a specific internal state without using global variables:
def persistent_counter(start):
count = start
while True:
yield count # Pause here and return current count
count += 1 # Resume here next time, incrementing the saved 'count'
# Usage
counter = persistent_counter(10)
print(next(counter)) # Output: 10
print(next(counter)) # Output: 11
print(next(counter)) # Output: 12
In the example above, the count variable lives inside the function scope. Because we use yield, the function doesn't reset count to 10 every time we call next(). Instead, it maintains the value of count throughout the entire lifecycle of the generator object.
This state persistence is what makes yield so powerful for creating custom sequences. You aren't just processing a static list; you are defining an ongoing process that manages its own memory and internal progress, which is significantly more efficient than creating large lists in memory for data that could be generated on the fly.
Key Takeaway: The yield keyword turns a function into a generator, allowing it to pause execution and preserve the values of local variables between iterations.