Generator Basics
What is a Generator?
In Python, a generator is a special type of function that returns an iterator object. Unlike regular functions that return a complete result set at once, generators can pause and resume their execution, yielding values one at a time.
Key Characteristics of Generators
Generators have several unique properties:
Property |
Description |
Memory Efficiency |
Generate values on-the-fly instead of storing entire sequence |
Lazy Evaluation |
Compute values only when requested |
State Preservation |
Remember their internal state between calls |
Creating Generators
There are two primary ways to create generators in Python:
Generator Functions
def simple_generator():
yield 1
yield 2
yield 3
## Using the generator
gen = simple_generator()
for value in gen:
print(value)
Generator Expressions
## Generator expression
squared_gen = (x**2 for x in range(5))
print(list(squared_gen)) ## [0, 1, 4, 9, 16]
Generator Workflow
graph TD
A[Generator Function Called] --> B[Execution Starts]
B --> C{Yield Statement}
C --> |Pauses Execution| D[Returns Value]
D --> E[Resumes When Next Value Requested]
E --> C
Advanced Generator Concepts
Generator Methods
Generators support methods like .send()
, .throw()
, and .close()
for advanced control flow.
def interactive_generator():
while True:
x = yield
print(f"Received: {x}")
gen = interactive_generator()
next(gen) ## Prime the generator
gen.send(10) ## Sends value to generator
Generators are ideal for:
- Processing large datasets
- Implementing custom iterators
- Creating infinite sequences
- Reducing memory consumption
By understanding generators, you can write more memory-efficient and elegant Python code. LabEx recommends practicing these concepts to master generator programming.