Python Generators
Generators provide lazy evaluation for memory efficiency.
Creating Generators
# Generator function
def count_up_to(n):
i = 1
while i <= n:
yield i
i += 1
# Usage
for num in count_up_to(5):
print(num)
# Generator expression
squares = (x**2 for x in range(1000000))
Benefits
- Memory efficient for large datasets
- Lazy evaluation
- Infinite sequences
Discussion 0
No comments yet. Be the first to start the discussion!
Leave a Comment