What Does The “yield” Keyword Do in Python?

In this post, we will learn What the “yield” keyword does in Python where it is used for creating a generator function. Where after this statement is executed it suspends the execution of the function and sends the value back to the function caller, Although it has the authority and functionality to resume the function again from where it left once I get back.


Yield Function

After the encounter of the word and the generator function is created it returns a generator object which could be iterated though out using for loop or the next() function. Each time the next value is requested from the generator, the function resumes execution from where it left off and continues until the next “yield” statement is encountered, at which point the value is returned to the caller.

Here a pseudo code for the example is given which we can refer to learn more about the same where a sequence of even numbers is generated:

def even_ numbers( n):
    for i in range( n):
        if i % 2 == 0:
            yield i

Here when we call the function with an input of 12 it will produce even numbers from 0 to 10. And here we will see an example of the same using a traditional for loop to get the even numbers from zero to 12.

>>> for num in even_ numbers(12):
...     print( num)

The point to be noted here is that the function is only executed when the generator object will be iterated over, and the function’s state is retained between iterations. Which allows for the efficient use of memory and computation when working with large sequences of data.

Generally, we use it at the place of for loop when we have to iterate through a list as it is more effective as compared to for loop which make the iteration quicky and it does not required any external variable to iterate.


To learn more about What The “yield” Keyword Does in Python visit: The yield key word use an example along with an explanation

To learn more about python problems and solutions along with concepts tutorials visit: How To Pass-Variables From A Java & Python Client To A Linux/Ubuntu Server Which Is Running C?

To learn more about different other programming languages like Java, MongoDB, MySQL, and python as the solutions to the problems faced during solving it and to get clear on the concepts related to them go ahead with: beta python programming languages Solutions



Leave a Comment

%d bloggers like this: