Yield statement in python suspend the function execution and return a value to the caller function.

By using yield the function state remains preserved so on another call, the function starts its execution from the point where its last execution was suspended.

Consider the following example of yield in python.

def myFunction():
  print("First Hello")
  yield 1
  print("Second Hello")
  yield 2
  print("Third Hello")

for x in myFunction():

myFunction()  #no-output


First Hello
Second Hello
Third Hello

But simply calling the function (i.e myFunction()) will not output any result because on using yield the function becomes a generator.

Let’s understand what is Generator in python step by step.


When we want to read certain values multiple times we store it usually as a list.

myList = [1, 5, 9, 7]
for x in myList:

Here myList is an Iterable. It is very useful when we want to read it multiple times. But sometimes with large numbers of values, it becomes inefficient when it is only needed to be read once or hardly twice.

Here comes the python generator in rescue.


Generators are iterators, a kind of iterable you can only iterate over once. Generators do not store all the values in memory, they generate the values on the fly.

A generator is created using () whereas a list is created using [].

Recommended: List Comprehension

myGenerator = (x*x for x in range(5))

print("First call")
for x in myGenerator:

print("Second call")
for x in myGenerator:


First call
Second call

Notice the second call does give any output because a generator can be used only once.


yield is like return but it makes the function to return a generator instead of some value.

In the first example when we called myFunction() we didn’t get any output because myFunction() returns a generator, hence it needs to be iterated using for … in … in python.

To master yield, you must understand that when you call the function, the code you have written in the function body does not run. The function only returns the generator object, this is a bit tricky 🙂

myFunction() gets replaced by a generator and on each successive call code upto next yield gets executed and the yield value is returned, unless there is no more return or yield in the function.

So the output which we got can be analyzed as

First Hello      ---> printed by the function/generator on first call
1                ---> print(x) in for loop
Second Hello     ---> printed by the function/generator on second call
2                ---> print(x) in for loop
Third Hello      ---> printed by the function/generator on third call

Hope you got some idea about yield in python. If you still have any doubts or suggestion then comment below.

Leave a Reply