I am Utpal Vishwas from Uttar Pradesh. Have completed my B. Tech. course from MNNIT campus Prayagraj in 2022. I have good knowledge of computer networking.
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
Liked By
Write Answer
What is the use of the "yield" keyword in Python?
Join MindStick Community
You have need login or register for voting of answers or question.
Aryan Kumar
17-Apr-2023The 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.
Krishnapriya Rajeev
12-Apr-2023The 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: