WHAT IS YIELD IN PYTHON
In this article, we will see what is yield in Python, how to use it and some examples.
yield is a keyword in Python that is used to return from a function without destroying the states of its local variable and when the function is called, the execution starts from the last yield statement. Any function that contains a yield keyword is termed as generator. Hence, yield is what makes a generator.
def even(lis): for k in lis: if k % 2 == 0: yield k test = [1, 3, 6, 8, 9] print("Original list: " + str(test)) print("Even number(s) in test: ", end = " ") for i in even(test): print(i, end=" ")
Original list: [1, 3, 6, 8, 9] Even number(s) in test: 6 8
Using a yield statement in a function definition is sufficient to cause that definition to create a generator function instead of a normal function. The yield statement suspends the function’s execution and sends a value back to the caller, but retains enough state to enable the function to resume where it is left off