Practical Iteration Patterns
Comprehension Techniques
Tuple Comprehension
## Create tuple with squared numbers
squared_numbers = tuple(x**2 for x in range(5))
print(squared_numbers) ## (0, 1, 4, 9, 16)
Filtering Iterations
Conditional Iteration
numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
even_numbers = tuple(num for num in numbers if num % 2 == 0)
print(even_numbers) ## (2, 4, 6, 8, 10)
Mapping Elements
temperatures = (32, 68, 86, 104)
celsius = tuple(round((f - 32) * 5/9, 1) for f in temperatures)
print(celsius) ## (0.0, 20.0, 30.0, 40.0)
Iteration Flow
graph TD
A[Tuple Iteration] --> B{Iteration Pattern}
B --> |Comprehension| C[Transform Elements]
B --> |Filtering| D[Select Specific Elements]
B --> |Mapping| E[Convert Element Types]
Advanced Iteration Strategies
matrix = ((1, 2), (3, 4), (5, 6))
flattened = tuple(num for row in matrix for num in row)
print(flattened) ## (1, 2, 3, 4, 5, 6)
Pattern |
Memory Efficiency |
Readability |
Complexity |
List Comprehension |
Moderate |
High |
Low |
Generator Expression |
Excellent |
High |
Low |
Explicit Loop |
Good |
Medium |
Medium |
Practical Use Cases
- Data Preprocessing
- Mathematical Transformations
- Filtering Collections
Best Practices
- Use generator expressions for large datasets
- Prefer comprehensions for simple transformations
- Avoid complex logic in comprehensions
At LabEx, we recommend mastering these iteration patterns for efficient Python programming.