Generators
Generators are a simpler way to create iterators. They use the yield keyword to produce a series of values lazily, which means they generate values on the fly and do not store them on memory.
Pratica usage:
- Read large files without store they entirely in memory
| def square(n):
"""A simple generator that yields the square of a number."""
for i in range(n):
yield i * i
squares = square(5)
squares
|
<generator object square at 0x7ff0d4143030>
| try:
while True:
print(next(squares))
except StopIteration:
print("Reached the end of the generator.")
|
0
1
4
9
16
Reached the end of the generator.