12. Generators With Yield
Generators are functions that use yield to produce a sequence of values lazily.
Example
def count_up_to(n):
i = 1
while i <= n:
yield i
i += 1
for number in count_up_to(5):
print(number)
Benefits
- Save memory (values produced one at a time).
- Easy to write compared to custom iterators.
Wrap-Up
- Use
yieldin functions to create generators.