what is yield in python

1 year ago 34
Nature

In Python, the yield keyword is used to create a generator function, which is a type of function that is memory efficient and can be used like an iterator object. When a function that contains a yield statement is called, it returns a generator object to the caller instead of simply returning a value. The yield keyword controls the flow of a generator function, and as soon as a yield statement is encountered, the execution of the function halts and returns a generator iterator object. The key difference between yield and return is that yield can produce a sequence of values, whereas return sends a specified value back to its caller. We should use yield when we want to iterate over a sequence but don’t want to store the entire sequence in memory.

Here is an example of a generator function that uses yield to generate a sequence of Fibonacci numbers:

def fibonacci(n):
    temp1, temp2 = 0, 1
    total = 0
    while total < n:
        yield temp1
        temp3 = temp1 + temp2
        temp1 = temp2
        temp2 = temp3
        total += 1

fib_object = fibonacci(20)
print(list(fib_object))

This program generates the first 20 Fibonacci numbers using yield instead of return. The fibonacci() function is defined like a normal function, but whenever it needs to generate a value, it does so with the yield keyword. The list() function is used to convert the generator object returned by fibonacci() into a list of values.