Practical Iteration Patterns
Common Iteration Techniques
1. Sequential Iteration
## Basic sequential iteration
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruit)
2. Enumerate Iteration
## Tracking index during iteration
fruits = ['apple', 'banana', 'cherry']
for index, fruit in enumerate(fruits):
print(f"Index {index}: {fruit}")
Advanced Iteration Patterns
Lazy Iteration with Generators
def infinite_counter():
num = 0
while True:
yield num
num += 1
## Memory-efficient infinite sequence
counter = infinite_counter()
print(next(counter)) ## 0
print(next(counter)) ## 1
Iteration Strategy Comparison
Pattern |
Use Case |
Memory Efficiency |
Performance |
List Iteration |
Small collections |
Low |
Moderate |
Generator |
Large/Infinite sequences |
High |
Excellent |
Iterator |
Custom traversal |
Moderate |
Good |
Custom Iterator Patterns
class ReverseIterator:
def __init__(self, data):
self.data = data
self.index = len(data)
def __iter__(self):
return self
def __next__(self):
if self.index > 0:
self.index -= 1
return self.data[self.index]
raise StopIteration
## Reverse iteration
reverse_list = ReverseIterator([1, 2, 3, 4, 5])
for num in reverse_list:
print(num) ## Prints: 5, 4, 3, 2, 1
Iteration Flow Diagram
graph TD
A[Start Iteration] --> B{Has More Elements?}
B -->|Yes| C[Process Current Element]
C --> D[Move to Next Element]
D --> B
B -->|No| E[End Iteration]
Advanced Iteration Techniques
Zip Iteration
names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 35]
for name, age in zip(names, ages):
print(f"{name} is {age} years old")
Filter Iteration
def is_even(num):
return num % 2 == 0
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = filter(is_even, numbers)
print(list(even_numbers)) ## [2, 4, 6]
LabEx Pro Tip
LabEx recommends mastering different iteration patterns to write more efficient and readable Python code.
- Use generators for large datasets
- Prefer iterator methods over list comprehensions
- Implement custom iterators for complex traversal logic