Yield and Generator Functions
Understanding the Yield Keyword
The yield keyword is the core mechanism that transforms a regular function into a generator function. Unlike return, which terminates function execution, yield pauses the function and preserves its state.
Basic Yield Syntax
def simple_generator():
yield 1
yield 2
yield 3
## Creating a generator object
gen = simple_generator()
Yield Behavior Comparison
| Feature |
Return |
Yield |
| Execution |
Terminates Function |
Pauses Function |
| Memory |
Creates Entire List |
Generates Values On-Demand |
| State |
Resets |
Preserves |
Advanced Yield Techniques
Multiple Yield Statements
def fibonacci_generator(limit):
a, b = 0, 1
while a < limit:
yield a
a, b = b, a + b
for num in fibonacci_generator(10):
print(num)
Generator Function Workflow
graph TD
A[Generator Function Called] --> B[First Yield Encountered]
B --> C[Value Returned]
C --> D[Execution Paused]
D --> E[Next Iteration Requested]
E --> F[Resumes from Last State]
F --> G[Continues Until Exhausted]
Yield with Conditional Logic
def even_numbers(limit):
for num in range(limit):
if num % 2 == 0:
yield num
## Generates only even numbers
gen = even_numbers(10)
Generator Function Characteristics
- Uses
yield instead of return
- Maintains internal state
- Supports lazy evaluation
- Can be iterated multiple times
Generators are memory-efficient and ideal for:
- Large datasets
- Infinite sequences
- Stream processing
At LabEx, we emphasize the power of generators for creating efficient and scalable Python applications.
Generator vs Regular Function
## Regular Function
def list_squares(n):
return [x**2 for x in range(n)]
## Generator Function
def generator_squares(n):
for x in range(n):
yield x**2
Best Practices
- Use generators for memory-intensive operations
- Prefer generators when processing large datasets
- Combine with other iterators and generators