Practical Iteration Patterns
Comprehension Techniques
List Comprehension
A concise way to create lists:
## Basic list comprehension
squares = [x**2 for x in range(10)]
print(squares)
## Conditional list comprehension
even_squares = [x**2 for x in range(10) if x % 2 == 0]
print(even_squares)
Dictionary Comprehension
Creating dictionaries efficiently:
## Dictionary from two lists
names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 35]
name_age_dict = {name: age for name, age in zip(names, ages)}
print(name_age_dict)
graph LR
A[Input Iterable] --> B[Transformation Function]
B --> C[Transformed Output]
C --> D[New Iterable]
Map Function
Applying functions to iterables:
## Transforming list elements
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers))
print(squared)
Filter Function
Selecting elements based on conditions:
## Filtering even numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers)
Advanced Iteration Techniques
Technique |
Description |
Use Case |
Enumerate |
Index tracking |
Accessing index during iteration |
Zip |
Parallel iteration |
Combining multiple iterables |
Itertools |
Advanced iteration |
Complex iteration patterns |
Powerful iteration tools:
import itertools
## Combining iterables
names = ['Alice', 'Bob']
ages = [25, 30]
combined = list(itertools.product(names, ages))
print(combined)
## Permutations
items = [1, 2, 3]
perms = list(itertools.permutations(items))
print(perms)
Generator Expressions
Memory-efficient iteration:
## Generator expression
gen = (x**2 for x in range(10))
print(list(gen))
Reducing Iteration Complexity
Functional Approach
Using functools
for complex iterations:
from functools import reduce
## Calculating sum using reduce
numbers = [1, 2, 3, 4, 5]
total = reduce(lambda x, y: x + y, numbers)
print(total)
Key Iteration Patterns
- Comprehensions for concise collection creation
- Functional transformation of iterables
- Memory-efficient generator expressions
Note: LabEx encourages exploring these patterns to write more pythonic code.