How to use `yield` to create a generator in Python?

Published on Aug. 22, 2023, 12:17 p.m.

To use yield to create a generator in Python, you define a generator function that uses the yield keyword to generate a series of values one at a time. When a generator function is called, it returns a generator object, which is an iterator that can generate the values on demand. Here is an example of how to create a generator that yields Fibonacci numbers:

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

fib = fibonacci()
for i in range(10):
    print(next(fib))

In this example, we define a generator function fibonacci() that uses a while loop to generate an infinite series of Fibonacci numbers. Each time the yield statement is encountered, the current value of a is returned as the next value in the series, and the function is paused until the next time next() is called on the generator object. To use the generator, we create a generator object fib by calling the fibonacci() function, and then we use a for loop to print the first 10 values in the series by calling next() on the generator object. The output of this code would be:

0
1
1
2
3
5
8
13
21
34

This is just one example of how to use yield to create a generator in Python. You can use the same principle to create generators that generate any sequence of values you need.