Difference Between yield and return in Python

Difference Between yield and return in Python: A yield statement is used to define generators in Python. The yield statement suspends execution of a function. Then sends a value back to the caller while saving state. The whole generator itself can still be resumed after the return value is obtained.

A return statement ends the execution of the function and sends a value back to the caller. Without it, your function returns nothing.

Continue reading to know more about when to use yield and when to use return.

What is Python Yield?

The yield statement is used in Python generators to replace the return of a function to send a value back to its caller without destroying local variables.

To better understand what role the yield statement plays in Python programming, you have to understand what generators are. Generator functions are produced by definition just like regular functions but contain a “yield” statement. This begins with the keyword “yield” which specifies the generator object to be returned to the caller.

We can also say that the generator is a special function in Python that returns a generator object to the caller rather than a data value.

The yield keyword has the unique capability of stopping the execution of the function, saving state, and later resuming.

What is Python Return?

The return statement, unlike the yield statement, exits from a function, handing back a value to its caller. Functions return a value back to their callers and those that are more procedural in nature do not explicitly return anything at all.

While a function can have multiple return statements, only one of them can be called for any given invocation of the function.

Typically, a return statement appears at the very end of a function block to return the final result of executing all statements contained in that function.

However, it may also appear earlier in the function block to stop the execution of all subsequent statements in that block. This immediately resumes the execution of the program at the caller. When no value is specified, the equivalent return object type in Python is “None”.

Find example at https://pythontips.com/2013/09/29/the-python-yield-keyword-explained/

Leave a Reply

Discover more from BHUTAN IO

Subscribe now to keep reading and get access to the full archive.

Continue reading

Scroll to Top