Generator Basics
What is a Generator?
A generator in Python is a special type of function that returns an iterator object, allowing you to generate a sequence of values over time, rather than computing them all at once and storing them in memory. Generators provide a memory-efficient way to work with large datasets or infinite sequences.
Creating Generators
Generator Functions
Generators are created using the yield
keyword instead of return
. When a generator function is called, it returns a generator object without actually starting the function's execution.
def simple_generator():
yield 1
yield 2
yield 3
## Create generator object
gen = simple_generator()
Generator Expressions
Similar to list comprehensions, generator expressions provide a concise way to create generators:
## Generator expression
squared_gen = (x**2 for x in range(5))
Generator Behavior
Lazy Evaluation
Generators use lazy evaluation, meaning values are generated on-the-fly:
graph LR
A[Generator Created] --> B[Value Generated Only When Requested]
B --> C[Next Value Generated on Next Iteration]
Iteration Mechanism
Generators can be iterated using next()
or in a for
loop:
def countdown(n):
while n > 0:
yield n
n -= 1
## Iteration methods
for num in countdown(3):
print(num)
## Using next()
gen = countdown(3)
print(next(gen)) ## 3
print(next(gen)) ## 2
Key Characteristics
Feature |
Description |
Memory Efficiency |
Generates values one at a time |
Iteration |
Can be iterated only once |
State Preservation |
Remembers its state between calls |
Use Cases
- Working with large datasets
- Infinite sequences
- Pipeline processing
- Memory-constrained environments
Advanced Generator Techniques
Generator Chaining
def generator1():
yield from range(3)
def generator2():
yield from range(3, 6)
## Combining generators
combined = list(generator1()) + list(generator2())
print(combined) ## [0, 1, 2, 3, 4, 5]
Generators are particularly useful in LabEx environments where resource optimization is crucial. They provide a lightweight alternative to traditional list-based approaches, especially when dealing with large or complex data transformations.