Python | yield Keyword
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 a generator. Hence, yield is what makes a generator. The yield keyword in Python is less known off but has a greater utility which one can think of.
Code #1 : Demonstrating yield working
The original list is : [1, 4, 5, 6, 7] The even numbers in list are : 4 6
1 4 9 16 25 36 49 64 81 100
Advantages of yield:
- Since it stores the local variable states, hence overhead of memory allocation is controlled.
- Since the old state is retained, the flow doesn’t start from the beginning and hence saves time.
Disadvantages of yield:
- Sometimes, the use of yield becomes erroneous if the calling of function is not handled properly.
- Time and memory optimization has a cost of complexity of code and hence sometimes hard to understand the logic behind it.
The possible practical application is that when handling the last amount of data and searching particulars from it, yield can be used as we don’t need to look up again from start and hence would save time. There can possibly be many applications of yield depending upon the use cases.
The number of geeks in string is : 3
Last Updated on November 13, 2021 by admin