Practical Iteration Patterns
Fundamental Iteration Techniques
1. Basic for
Loop Iteration
## Simple list iteration
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruit)
## Dictionary iteration
student = {'name': 'John', 'age': 25, 'city': 'New York'}
for key, value in student.items():
print(f"{key}: {value}")
Advanced Iteration Strategies
2. List Comprehensions
## Transforming data
numbers = [1, 2, 3, 4, 5]
squared = [x**2 for x in numbers]
print(squared) ## [1, 4, 9, 16, 25]
## Filtering with comprehensions
even_numbers = [x for x in numbers if x % 2 == 0]
print(even_numbers) ## [2, 4]
3. Generator Expressions
## Memory-efficient iteration
gen = (x**2 for x in range(10))
print(list(gen)) ## [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Iteration Control Patterns
graph TD
A[Iteration Control] --> B[Enumerate]
A --> C[Zip]
A --> D[Filter]
A --> E[Map]
4. enumerate()
for Indexed Iteration
## Getting index and value
fruits = ['apple', 'banana', 'cherry']
for index, fruit in enumerate(fruits):
print(f"Index {index}: {fruit}")
5. zip()
for Parallel Iteration
## Combining multiple iterables
names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 35]
for name, age in zip(names, ages):
print(f"{name} is {age} years old")
Iteration Techniques Comparison
Technique |
Use Case |
Memory Efficiency |
Readability |
for Loop |
Basic iteration |
Medium |
High |
List Comprehension |
Transformation |
Low |
Medium |
Generator Expression |
Large datasets |
High |
Medium |
enumerate() |
Indexed access |
Medium |
High |
zip() |
Parallel iteration |
Medium |
High |
Advanced Iteration Patterns
import itertools
## Combining iterables
numbers = [1, 2, 3]
letters = ['a', 'b', 'c']
combined = list(itertools.product(numbers, letters))
print(combined)
7. Custom Iteration with __iter__()
and __next__()
class CustomRange:
def __init__(self, start, end):
self.current = start
self.end = end
def __iter__(self):
return self
def __next__(self):
if self.current >= self.end:
raise StopIteration
else:
self.current += 1
return self.current - 1
## Usage
custom_range = CustomRange(1, 5)
print(list(custom_range)) ## [1, 2, 3, 4]
Best Practices
- Choose iteration method based on specific requirements
- Consider memory efficiency
- Leverage built-in Python iteration tools
- LabEx recommends mastering multiple iteration techniques