What does the "yield" word do in Python

1 min

In Python, the "yield" keyword is used in the body of a function definition. When a function is called with a "yield" statement, it returns a generator object, but does not start execution immediately.

The function can be "resumed" from where it left off, each time the generator's next() method is called. This allows the function to produce a series of values over time, rather than computing them all at once and returning them in a list, for example.

For example, the following function uses "yield" to generate the sequence of Fibonacci numbers:

def fibonacci():
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b

And this can be used in the following way:

>>> fib = fibonacci()
>>> fib.next()
0
>>> fib.next()
1
>>> fib.next()
1
>>> fib.next()
2

It's also important to mention that when a function defined with yield is called, it returns a generator object, but does not start execution immediately. Execution only begins when the generator's next() method is called for the first time.