Practical Examples
Real-World Iterator Applications
Iterators are powerful tools for solving complex computational problems efficiently. This section explores practical scenarios where iterators shine.
1. Large File Processing
def log_line_generator(filename):
with open(filename, 'r') as file:
for line in file:
if 'ERROR' in line:
yield line.strip()
## Memory-efficient error log processing
def process_error_logs(log_file):
error_count = 0
for error_line in log_line_generator(log_file):
error_count += 1
print(f"Error detected: {error_line}")
return error_count
def data_transformer(raw_data):
for item in raw_data:
yield {
'processed_value': item * 2,
'is_positive': item > 0
}
## Example usage
raw_numbers = [1, -2, 3, -4, 5]
transformed_data = list(data_transformer(raw_numbers))
Iterator Design Patterns
graph TD
A[Iterator Pattern] --> B[Generator Functions]
A --> C[Custom Iterator Classes]
A --> D[Itertools Module]
3. Infinite Sequence Generation
def fibonacci_generator():
a, b = 0, 1
while True:
yield a
a, b = b, a + b
## Generate first 10 Fibonacci numbers
fib_sequence = list(itertools.islice(fibonacci_generator(), 10))
Approach |
Memory Usage |
Computation Speed |
Scalability |
List Comprehension |
High |
Fast |
Limited |
Generator |
Low |
Lazy |
Excellent |
Iterator |
Moderate |
Flexible |
Good |
4. Database Record Streaming
def database_record_iterator(connection, query):
cursor = connection.cursor()
cursor.execute(query)
while True:
record = cursor.fetchone()
if record is None:
break
yield record
## Efficient database record processing
def process_records(db_connection):
query = "SELECT * FROM large_table"
for record in database_record_iterator(db_connection, query):
## Process each record without loading entire dataset
process_record(record)
Advanced Iterator Techniques
Chaining Iterators
import itertools
def combined_data_source():
source1 = [1, 2, 3]
source2 = [4, 5, 6]
return itertools.chain(source1, source2)
Best Practices
- Use generators for memory-intensive operations
- Implement lazy evaluation when possible
- Leverage
itertools
for complex iterations
- Profile and optimize iterator performance
At LabEx, we encourage developers to master iterator techniques for writing efficient and scalable Python code.