Codzy

Generators

A generator produces values one at a time, only when they are needed, instead of creating everything at once. It saves a lot of memory with large amounts of data.

You create a generator with a function that uses yield instead of return: at each yield, the function hands out a value and pauses. You get the values with a for loop, next() or list(). There is also a short form: (n * n for n in range(4)).

def countdown(n):
    while n > 0:
        yield n
        n -= 1

for x in countdown(3):
    print(x)

gen = (n * n for n in range(4))
print(next(gen))
print(list(gen))

Start the lesson