yield (Python)

yield is the keyword that makes a function a generator function: calling it gives a generator instead of running the body. Each yield hands back a value and pauses the body, resuming from the same spot the next time a value is requested.

Python

Unlike return, which ends a function for good, yield lets a function produce many values over time while keeping its local state between calls.

Examples

Python

def evens():
    n = 0
    while True:
        yield n
        n += 2

gen = evens()
print(next(gen), next(gen), next(gen))

Output:

0 2 4

Learn it in a lesson

See also

Back to the Dictionary