Skip to content

Generators

Generators are functions return iterable results that do not execute until the next iteration is requested. This is achieved with the yield keyword which acts as a return. You can iterate over the function as you would any other iterable type. You can also manually request the next return value with the next function.

Some types can also be turned into generators with the iter function.

python
def create_cubes(n):
    for x in range(n):
        yield x**3

for x in create_cubes(10):
    print(x)

y = create_cubes(10)
print(y) # Generator function
print(next(y)) # First value, 0
print(next(y)) # POP! Second value, 1

# Can turn some types into generators with iter
s = "hello"
s_iter = iter(s)
print(next(s_iter)) # First value, h