Python -Yield Keyword
When we write a function, we normally use the return statement for returning the result from a function.
The yield keyword in python is also just like return which is used to return a value from a function but this keyword also maintains the state of the local variables of the function and the execution starts from the yield statement executed previously when the function is called again.
Let’s look at an example to understand what about yield keyword:
# generator to print odd numbers def print_odd(x_list): for i in x_list: if i % 2 != 0: yield i # initializing list x_list = [1, 4, 5, 6, 7, 8, 12] # printing initial list print ("The original list is : " + str(x_list)) # printing odd numbers print ("The odd numbers in list are : ", end = " ") for j in print_odd(x_list): print (j, end = " ")
In the code above we have defined a simple function which has a condition for finding the odd value and yielding the odd value of i.
When a yield statement is used in a function then it is called as Generator.
Advantages of yield:
- Memory distribution is controlled as it stores the local variable states.
- Since the old state is retained, flow doesn’t begin from the beginning and hence saves time.
Disadvantages of yield:
- Sometimes, the utilization of yield becomes erroneous if calling of function is not handled properly.
- The time and memory optimization has a cost of complexity of code and hence sometimes difficult to understand logic behind it.