Course Content
Python Programming Tutorial
About Lesson

yield Keyword in Python

When we write a function which should perform some operation and provide some result back, we generally use the return statement for returning the result.

The yield keyword in python is also used to return a value from a function(just like return) but this keyword also maintains the state of the local variables of the function and when the function is called again, the execution is started from the yield statement executed last time.

Let’s see a simple example and try to understand what yield keyword actually does:

def counter():
    x = 0
    while x < 5:
        yield x
        # incrementing the value of x
        x += 1
 

In the code above we have defined a simple function which has a while loop and is yielding the current value of x and then increments it.

First things first, when we use a yield statement in a function then the function is called as Generator, about which we will learn in the next tutorial.

A generator generates or yields values and cannot be called like a simple function rather it is called like an iterable i.e. by using a loop, for example a for loop.

Let’s see both the cases,

# calling the above function directly
print("Simple function call: ", counter())    # should 
print 0
# and now lets use a loop to print values print("Now lets try using a loop:") for y in counter(): print(y)
 

Simple function call: <generator object counter at 0x7f95fba4ba98> Now lets try using a loop: 0 1 2 3 4


Some Points to Remember about yield Keyword

Think of yield keyword as a smart return statement which remembers what it did the last time and continues from there the next time.

Like in the counter() function above, when we call it the first time, it will return 0, but when we call it next time, it will increment the value of x and then return 1, then we call it again, it will again increment the value of x and return the result 2 and so on until the loop is completed.

  1. When we use 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.
  2. Also, in consecutive calls the flow starts from the last yield statement executed which saves time.
  3. We can easily create iterable functions using yield keyword.

Time for some Examples!

As we mentioned above, by using the yield keyword we make our function an iterable. And we know that for an iterable, we can use the next() method for iterating to the next element. So let’s try to implement that in our first example.

Example 1:

In the example above, we have used multiple yield statement to save the state of the execution of the function(or generator) new_gen() such that the next time that function is called the execution begins from where it last left.

Try adding one more print(next(x)) statement to the above code and you will see the StopIteration exception which an iterator returns when there is no more data left to iterate over.

Example 2:

In this code example we will be using yield keyword in a function to count the occurence of a word in a sentence.

Using the yield keyword in above problem will help us simplify the code for searching a word in a list of words and increasing the count 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.

Similarly there are many use cases of the yield keyword. In our next tutorial we will learn about Generators which are the functions in which we use yield keyword. In the code example above, count_words is a generator.

error: Content is protected !!