Practical Looping Techniques
Comprehensive Looping Strategies
graph TD
A[Looping Techniques] --> B[List Comprehensions]
A --> C[Generator Expressions]
A --> D[Conditional Loops]
A --> E[Advanced Iteration]
List Comprehensions
Basic Syntax and Usage
## Simple list comprehension
squares = [x**2 for x in range(10)]
print(squares) ## Outputs: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
## Conditional list comprehension
even_squares = [x**2 for x in range(10) if x % 2 == 0]
print(even_squares) ## Outputs: [0, 4, 16, 36, 64]
Generator Expressions
Type |
Memory Efficiency |
Syntax |
Use Case |
List Comprehension |
Less Efficient |
[x for x in range()] |
Small Collections |
Generator Expression |
More Efficient |
(x for x in range()) |
Large Datasets |
## Memory-efficient iteration
sum_of_squares = sum(x**2 for x in range(1000000))
print(sum_of_squares)
Conditional Looping Techniques
Multiple Conditions
## Complex filtering
data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
filtered_data = [
x for x in data
if x > 3 and x < 8
]
print(filtered_data) ## Outputs: [4, 5, 6, 7]
Advanced Iteration Methods
Dictionary and Set Comprehensions
## Dictionary comprehension
student_scores = {'Alice': 85, 'Bob': 92, 'Charlie': 78}
passed_students = {
name: score for name, score in student_scores.items()
if score >= 80
}
print(passed_students)
Nested Comprehensions
## Matrix creation
matrix = [[x*y for x in range(3)] for y in range(3)]
print(matrix)
## Outputs: [[0, 0, 0], [0, 1, 2], [0, 2, 4]]
Comparing Loop Techniques
## Traditional loop
def traditional_square(n):
result = []
for x in range(n):
result.append(x**2)
return result
## List comprehension
def comprehension_square(n):
return [x**2 for x in range(n)]
## LabEx recommends list comprehensions for readability and performance
Best Practices
- Use list comprehensions for simple transformations
- Prefer generator expressions for large datasets
- Keep comprehensions readable
- Avoid complex nested comprehensions
Error Handling in Loops
## Safe iteration with error handling
def safe_process(items):
processed = []
for item in items:
try:
processed.append(item * 2)
except TypeError:
print(f"Skipping non-numeric item: {item}")
return processed
mixed_data = [1, 2, 'three', 4, 5]
result = safe_process(mixed_data)
print(result)
Key Takeaways
- Comprehensions provide concise, efficient looping
- Generator expressions save memory
- Conditional loops offer powerful filtering
- LabEx encourages mastering these techniques for Pythonic code