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.

Output

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 this what is a Generator in python step by step.

Iterable

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

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

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

Output

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

Yield

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

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

Leave a Reply

Close Menu