Yield in Python | Python Programming

Yield in Python: Yield in Python programming is a keyword same like return keyword. The only difference between the yield and return is that, return gives the final value after the function stop its execution but yield returns the generator object to the caller.

When function is called and during the execution if it finds a yield keyword, the execution stops and immediately it returns the generator object to the caller. Generators are nothing but just a special method that used to be iterated to get the values.

Syntax of Yield: 

yield expression

Python yields always returns Generator object and that object is used by Generators to return value.

Example 1: According to above statements, yield returns generator object. Let’s see by implementation.

#Example-1 to demonstrate the use of yield keyword

def pythonlobby():
    x = "This is Yield"
    yield x

print(pythonlobby())

Output:

#Output
<generator object pythonlobby at 0x7fd9eabddca8>

so output we get is the generator object. We didn’t get the value we passed to variable x. Let’s see same example using return keyword.

#Example-2 to demonstrate the use of yield keyword

def pythonlobby():
    x = "This is Return"
    return x

print(pythonlobby())

Output:

#Output
# This is Return

yield-in-python

Difference between Yield and Return

YIELD RETURN
Yield returns generator object. After function finish its complete execution, return gives the final value returned by function at the end.
Yield does not use any memory. Memory is used by return to store returned value.
Yield is useful while dealing with huge data. Return is convenient, while returning small data.
Execution of yield is faster as compared to return. Execution of return is slower as compared to yield.
Syntax: yield expression Syntax: return expression

 

Conclusion: Yield in Python programming is a keyword same like return keyword. The only difference, return gives the final value after the function stop its execution but yield returns the generator object. Yield does not store any value in memory but return require memory to store value. Yield is useful while working with large data. Return is useful while working with small data size.