The Yield keyword in Python is similar to a return statement used for returning values or objects in Python. However, there is a slight difference. The yield statement returns a generator object to the one who calls the function which contains yield, instead of simply returning a value.
The yield keyword is used in Python in order to create a generator function, i.e., one that can be used like an iterator object. In such a function, the yield keyword converts the expression following it into a generator object, which may be iterated over again and again to return the values contained inside it.
An example of a Python program implementing the yield keyword is:
# define the generator function
def generator_function():
yield “Apple”
yield “Banana”
yield “Carrot”
generator_object = generator_function()
print(type(generator_object))
# yield the different values inside the object
print(next(generator_obj)
print(next(generator_obj)
print(next(generator_obj)
# Output = <class ‘generator’>
Apple
Banana
Carrot
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
The Yield keyword in Python is similar to a return statement used for returning values or objects in Python. However, there is a slight difference. The yield statement returns a generator object to the one who calls the function which contains yield, instead of simply returning a value.
The yield keyword is used in Python in order to create a generator function, i.e., one that can be used like an iterator object. In such a function, the yield keyword converts the expression following it into a generator object, which may be iterated over again and again to return the values contained inside it.
An example of a Python program implementing the yield keyword is: