Return vs Yield in Python with examples
Python keywords are reserved words that are pre-defined to convey special meanings(functions) to the interpreter. In today’s tutorial, you will learn about two such keywords:
- Return
- Yield
Return vs Yield in functions
If you are familiar with functions and their usage in programming, you would have come across the return keyword too. The return keyword is usually used in Python functions to return a value at the end of the function.
The yield keyword, on the other hand, is used to return a series of values instead of a single value at the end of the function.
How is yield different from return?
When the yield keyword is used in a function, that function becomes a generator function.
If you are new to generator functions, you can read Using Generators inside Functions in Python .
On encountering the yield statement, the function pauses its execution and returns the value to the caller. The state of the function is then resumed and the execution continues. The same can be studied as follows:
def eg_func(): yield "a" yield "b" yield "c" generator_obj=eg_func() res=next(generator_obj) print(res) res=next(generator_obj) print(res) res=next(generator_obj) print(res)
Leave a Reply