What does the yield keyword do in python

Introduction

This is a frequently asked question in Python. In this article, I will only provide a short summary. For more details, you may refer to the full article here. So what is the deal about the yield keyword in Python ? The yield keyword in Python has to do with generator functions.

Let us define that…

Generator function

A generator function in Python has the same form of a regular function but the difference in syntax between a generator function and a regular function is that a yield statement is used instead of a return statement. A regular function returns a value but a generator function returns a generator object. Calling a generator function does not change the generator’s state.

Now the question is…

Why do we need that in the first place?, a regular function can do the job. Yes, it can but with generators, values are generated on the fly and there is no need to spare a huge amount of space to save all values in one shot but rather generate values based on need.

Here is an example borrowed from the full article…

Summary

As you can see, if we wanted to generated a range of odd numbers, we can do that on demand using the yield keyword instead of generating the whole list in one shot which requires more space.

That is it, thanks for visiting. For questions and feedback, please use the comments section

Tags:

Add a Comment

Your email address will not be published. Required fields are marked *