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?
- Difference between Yield and Return in Python
- Python in Keyword
- is keyword in Python
- finally keyword in Python
- Global keyword in Python
- Python | assert keyword
- Keyword Module in Python
- Python IMDbPY - Searching keyword
- Use of nonlocal vs use of global keyword in Python
- How to check if a string is a valid keyword in Python?
- Python | Passing dictionary as keyword arguments
- Python program to check if a given string is Keyword or not
- Python IMDbPY – Searching movies matching with keyword
- Reusable piece of python functionality for wrapping arbitrary blocks of code : Python Context Managers
- Python - Read blob object in python using wand library
- Python | Merge Python key values to list
- Python | Convert list to Python array
- Python | PRAW - Python Reddit API Wrapper
- MySQL-Connector-Python module in Python
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. 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.