Generator Basics
What are Generators?
Generators are a powerful feature in Python that provide a simple and memory-efficient way to create iterators. Unlike traditional 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
Lazy Evaluation
Generators use lazy evaluation, which means they generate values on-the-fly instead of storing them all in memory simultaneously.
def simple_generator():
yield 1
yield 2
yield 3
## Demonstrates lazy generation
gen = simple_generator()
print(next(gen)) ## Outputs: 1
print(next(gen)) ## Outputs: 2
Memory Efficiency
Generators are memory-efficient, especially when dealing with large datasets:
graph TD
A[Large Dataset] --> B[Traditional List]
A --> C[Generator]
B --> D[Entire Data Loaded in Memory]
C --> E[Values Generated On-Demand]
Generator Functions vs Generator Expressions
Generator Functions
Functions using yield
keyword create generator functions:
def countdown(n):
while n > 0:
yield n
n -= 1
for num in countdown(5):
print(num) ## Outputs: 5, 4, 3, 2, 1
Generator Expressions
Compact, one-line generator creation:
squares = (x**2 for x in range(5))
print(list(squares)) ## Outputs: [0, 1, 4, 9, 16]
Generator Methods
Method |
Description |
Example |
next() |
Retrieves next value |
value = next(generator) |
send() |
Sends a value into generator |
generator.send(value) |
close() |
Terminates generator |
generator.close() |
Advanced Generator Concepts
Generator Pipelines
Generators can be chained to create data processing pipelines:
def process_data(data):
for item in data:
yield item * 2
def filter_even(data):
for item in data:
if item % 2 == 0:
yield item
numbers = range(10)
processed = process_data(filter_even(numbers))
print(list(processed)) ## Outputs: [0, 4, 8, 12, 16]
Best Practices
- Use generators for large datasets
- Prefer generator expressions for simple iterations
- Close generators explicitly when done
Learning with LabEx
At LabEx, we recommend practicing generator concepts through hands-on coding exercises to build practical skills in Python programming.