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. 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, flow doesn’t start from the beginnning and hence saves time.
Disadvantages of yield:
- Sometimes, the use of yield becomes erroneous is calling of function is not handled properly.
- The time and memory optimization has a cost of complexity of code and hence sometimes hard to understand 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 lookup again from start and hence would save time. There can possibly be many application of yield depending upon the use cases.
The number of geeks in string is : 3
- When to use yield instead of return in Python?
- Global keyword in Python
- finally keyword in Python
- Python | assert keyword
- How to check if a string is a valid keyword in Python?
- Python program to check if a given string is Keyword or not
- Important differences between Python 2.x and Python 3.x with examples
- Reading Python File-Like Objects from C | Python
- Python | Add Logging to a Python Script
- Python | Set 4 (Dictionary, Keywords in Python)
- Python | Sort Python Dictionaries by Key or Value
- Python | Add Logging to Python Libraries
- zip() in Python
- Python | a += b is not always a = a + b
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.