What is the difference between return and yield in Python?

Tracyrenee
2 min readMar 25, 2022

I have been working with the yield statement within a function, and not being quite sure how it differed from the return statement, I decided to research the matter. I looked on the Geek for Geeks website and learned quite a bit about the yield statement and how it differs from the return statement.

The yield statement

A yield statement is generally used to convert a regular Python function to a generator. A generator is a function that returns an iterator that can be iterated over one value at a time.

A yield replaces a return of a function to suspend its execution without destroying local variables.

A yield is used when the generator returns an intermediate result to the caller.

Code written after the yield statement will be executed in the next function call.

A yield can be run multiple times.

And finally, a yield statement function is executed from the last state from whence the function was passed.

An example of how a yield can be used in a function can be seen in the screenshot of matplotlib’s oscilloscope emitter function below:-

--

--

Tracyrenee

I have close to five decades experience in the world of work, being in fast food, the military, business, non-profits, and the healthcare sector.