What is yield function and its examples?

n programming, the yield keyword is used in Python to create a generator function. It allows the function to produce a sequence of values one at a time, and each time a value is yielded, the function’s state is saved, allowing it to be resumed from where it left off.

https://docs.python.org/3/reference/simple_stmts.html#the-yield-statement

Here’s an example to illustrate the usage of yield:

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

# Using the generator
fib_gen = fibonacci()
for _ in range(10):
    print(next(fib_gen))

In this example, the fibonacci function is a generator that generates Fibonacci numbers. It uses an infinite loop to keep generating numbers indefinitely. The yield statement is used to yield the current Fibonacci number, and the function’s state is saved.

By calling next(fib_gen) in the for loop, we retrieve the next value from the generator. The loop runs 10 times, so it prints the first 10 Fibonacci numbers:

0
1
1
2
3
5
8
13
21
34

The generator function is paused after each yield statement, allowing you to iterate over the sequence of values without generating all the numbers at once. This is particularly useful when dealing with large or infinite sequences, as it conserves memory by generating values on the fly.

Leave a Reply

Your email address will not be published. Required fields are marked *