/  Technology   /  What does the yield keyword do in Python?
What does the yield keyword do in Python

What does the yield keyword do in Python?


Yield is a keyword that is used to return a value from a function without destroying the states of its local variable. Any function that contains a yield keyword is generally called a generator

When we replace return with yield in a function, it causes the function to hand back the iterator to its caller, which leads to the yield preventing the function from exiting until the next time the function is called. When called, it will start executing from the point where it stopped earlier. And how does this happen? Let’s see that.

When we use the yield keyword to return data from a function, it starts storing the states of the local variable, as a result, the overhead of memory allocation for the variable in consecutive calls is saved. Also, as the old state is retained in consecutive calls, the flow starts from the last yield statement executed, which in turn, saves time.


Note: A generator yields values and cannot be called like a simple function, instead it is called like an iterable, i.e. by using a loop, such as a for loop. Iterable functions can be simply created using the yield keyword.


#Code to generate cubes from 1 to 300 using yield and hence a generator

>>def cubes():                # An infinite generator function
            i = 1
            while True:
                           yield i*i*i                                      
                           i += 1                # Next execution resumes from this point         
>>for n in cubes():
            if n > 300:




Observe that the function cubes() printed until the first yield. Now, if you iterate again, it doesn’t start from the beginning, it starts from where it left off.


return sends a specific value back to its caller function, whereas yield produces a sequence of values. We should use yield when our need is to iterate over a sequence, but don’t wish to store the entire sequence in memory.


The yield keyword in Python is not so often used or not so well known, but it is of greater use if one uses it correctly.


Leave a comment