Yield keyword in Python
In this article, we will learn about the "yield" keyword available in Python. We will use custom examples to see the working of yield keyword. Let's first have a quick look over what is a yield keyword and why it is used in Python.
What is yield in Python?
Yield is a keyword in the Python programming language. The yield keyword in Python is similar to the return keyword. Yield is used to return a value from a function as well as it maintains the state of the local variables of the function and when the function is called again, the execution is started from the last yield statement. This keyword is not in use but it has its own uniqueness. The function in which yield keyword is used, that function is known as a
Example: Working of Yield
The below example uses yield in a function. We have defined a simple function that has a while loop and incrementing the value of x by 1. The function is yielding the current value of x.
x = 0
while(x < 5):
# incrementing the value of x
x += 1
Characteristics of the yield keyword
1. It is like a smart
return statement that remembers the last operation and continues from there the next time.
2. When yield returns any value, it stores the state of the local variable as a result of which the overhead of memory allocation for the local variable in consecutive calls is saved.
3. During consecutive calls to the generator function, the flow starts from the last yield statement executed which saves time.
4. We can easily create iterable functions using the yield keyword.
5. Sometimes, the output of the yield keyword becomes inaccurate due to the handling of multiple calling functions.
Usage of "yield" over "return" in Python
The yield keyword suspends the function's execution and sends an element back to the caller, however it preserves the last state of the function so that it resumes later from that point. When continued, the function proceeds with execution following the last yield run. This permits the code to create a progression of values, instead of sending them like a list.
#calling of above defined function
for x in func():
Return keyword returns a specific value back to the caller whereas Yield produces a sequence of elements and it is used when we want to iterate over a sequence instead of storing the entire sequence in the memory.
Different Applications of the yield keyword
Example: Iterating over elements using next()
We know that using the
yield keyword the function acts like an iterable. For an iterable, we use the
next() method for iterating to the next element. The below example uses multiple
yield statements to save the state of the execution of the generator function
func() such that the next execution begins from where it last left. If you try to add one more
print statement to the code, you will see the
StopIteration exception. The iterator returns this exception because there is no more data left to iterate over.
# A simple generator function
x = 1
# Generator function contains yield statements
x += 1
x += 1
r = func()
# calling next on variable r
Traceback (most recent call last):
File "/home/ccff3d0168203375859caeac5f48f378.py", line 24, in <module>
Example: Count the occurrences of words using yield
The below example uses
yield keyword in a function to count the occurrences of a word in a sentence. yield keyword makes it simple to search for a word in a list. It also increases the count of the word at the same time because
yield keyword will remember the last state and hence it will not iterate over the words which are already checked.
# function to count number of times a word occurs
def count(string, word):
for i in string:
if(i == word):
# initializing the string
string = "Almost nothing was more annoying than having our wasted time wasted on something not worth wasting it on."
# look for the word
word = "wasted"
# initialize count
c = 0
# using split to break the sentence into list of words
for j in count(string.split(), word):
c += 1
print ("The count is- ",c)
The count is- 2
In this article, we learned about
yield keyword in Python. We also learned about
generators and how a generator function is called. We saw different examples of yield keyword over return to better understand the functioning of yield.