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
- Python | Functions | Question 4
- Python | Functions | Question 5
- Python | Functions | Question 6
- Python lambda (Anonymous Functions) | filter, map, reduce
- *args and **kwargs in Python
- join() function in Python
- Python reversed() function
- Python | startswith() and endswith() functions
- Python | fsum() function
- Python __iter__() and __next__() | Converting an object into an iterator
- Monkey Patching in Python (Dynamic Behavior)
- Python | tuple() Function
- Difference between Method and Function in Python
- Python | TextBlob.word_counts() method
- Python Number | uniform() method
- Python Number | fabs() method
- Python Strings encode() method
- Python Strings decode() method
- Python 3 Strings | expandtabs() method
- Default arguments 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 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.