Control Flow: Iterators, List Comprehensions & Generator Expressions
1Concept
List comprehensions [x for x in seq] provide concise mapping/filtering. Generators (using yield or (x for x in seq)) create lazy iterators evaluated on-demand in O(1) memory.
2Architecture Diagram
List Comprehension [x*2 for x in seq] ──► Allocates full list in RAM immediately Generator Expression (x*2 for x in seq) ──► Lazily yields items 1-by-1 (O(1) memory!)
3Code Example
Stage 0 Language Foundations
# List comprehension (Eager)
squares = [x ** 2 for x in range(1, 6) if x % 2 == 1]
print(f"Odd squares list: {squares}")
# Generator function (Lazy)
def fibonacci(limit):
a, b = 0, 1
for _ in range(limit):
yield a
a, b = b, a + b
print("Fibonacci generator sequence:")
for num in fibonacci(7):
print(num, end=" ")
print()4Expected Output
Odd squares list: [1, 9, 25] Fibonacci generator sequence: 0 1 1 2 3 5 8
5Key Takeaways
- ✓Use generator expressions for large datasets to prevent RAM exhaustion.
- ✓for-loops in Python support an optional 'else:' block that executes if no break occurred.
- ✓yield pauses execution and preserves function stack frame state.