Skip to content

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
1
2
3
4
5
6
7
8
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

1
2
3
4
5
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.