Iteration Patterns
Common Iteration Techniques
List Comprehensions
List comprehensions provide a concise way to create lists based on existing iterables:
## Create a list of squared numbers
squares = [x**2 for x in range(10)]
print(squares)
Generator Expressions
Similar to list comprehensions, but more memory-efficient:
## Generate squared numbers without storing entire list
squared_gen = (x**2 for x in range(10))
for value in squared_gen:
print(value)
Advanced Iteration Patterns
Nested Iterations
Handling multiple nested collections:
## Nested iteration example
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for row in matrix:
for element in row:
print(element)
Zip Function
Combining multiple iterables:
## Parallel iteration
names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 35]
for name, age in zip(names, ages):
print(f"{name} is {age} years old")
Iteration Control Structures
Conditional Iterations
## Filtering during iteration
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = [num for num in numbers if num % 2 == 0]
print(even_numbers)
Breaking and Continuing
## Using break and continue
for num in range(10):
if num == 3:
continue ## Skip 3
if num == 7:
break ## Stop at 7
print(num)
Specialized Iteration Techniques
Dictionary Iteration
## Iterating through dictionaries
student_scores = {'Alice': 85, 'Bob': 92, 'Charlie': 78}
## Iterating through keys
for name in student_scores:
print(name)
## Iterating through key-value pairs
for name, score in student_scores.items():
print(f"{name}: {score}")
Iteration Patterns Comparison
Pattern |
Memory Efficiency |
Readability |
Use Case |
List Comprehension |
Moderate |
High |
Creating lists |
Generator Expression |
High |
High |
Large datasets |
Nested Iteration |
Low |
Moderate |
Complex collections |
graph TD
A[Iteration Patterns] --> B[List Comprehensions]
A --> C[Generator Expressions]
A --> D[Nested Iterations]
A --> E[Conditional Iterations]
LabEx Insight
At LabEx, we emphasize mastering these iteration patterns to write more efficient and readable Python code.
Advanced Considerations
- Generator expressions are more memory-efficient
- Use appropriate iteration technique based on data size
- Avoid unnecessary nested loops
Error Handling in Iterations
## Safe iteration with error handling
try:
for item in some_iterable:
process_item(item)
except StopIteration:
print("Iteration completed")