Practical Iteration Patterns
List Comprehensions
Basic Syntax
## Simple list comprehension
squares = [x**2 for x in range(10)]
print(squares)
Conditional List Comprehension
## Filtering with list comprehension
even_squares = [x**2 for x in range(10) if x % 2 == 0]
print(even_squares)
Dictionary Comprehensions
## Creating dictionary from lists
names = ['Alice', 'Bob', 'Charlie']
name_lengths = {name: len(name) for name in names}
print(name_lengths)
Iteration Techniques
Zip Function
## Parallel iteration
names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 35]
for name, age in zip(names, ages):
print(f"{name} is {age} years old")
graph TD
A[Itertools] --> B[Infinite Iterators]
A --> C[Finite Iterators]
A --> D[Combinatoric Iterators]
Practical Examples
import itertools
## Combining multiple iterables
for item in itertools.chain([1, 2, 3], ['a', 'b', 'c']):
print(item)
## Grouping elements
data = [1, 1, 2, 3, 3, 3, 4, 4]
for key, group in itertools.groupby(data):
print(f"Key: {key}, Group: {list(group)}")
Advanced Iteration Patterns
Nested Iteration
## Nested list comprehension
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened = [num for row in matrix for num in row]
print(flattened)
Pattern |
Memory Efficiency |
Readability |
Performance |
For Loop |
Medium |
High |
Medium |
List Comprehension |
Low |
High |
Fast |
Generator Expression |
High |
Medium |
Efficient |
Error Handling in Iterations
def safe_iteration(iterable):
try:
for item in iterable:
## Process item
print(item)
except StopIteration:
print("Iteration complete")
except Exception as e:
print(f"An error occurred: {e}")
Functional Iteration Techniques
Map Function
## Applying function to iterable
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers))
print(squared)
Filter Function
## Filtering iterable
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers)
Best Practices
- Use appropriate iteration technique for each scenario
- Prefer comprehensions for simple transformations
- Leverage itertools for complex iterations
- Consider memory efficiency
LabEx recommends practicing these patterns to become proficient in Python iteration techniques.