The yield statement suspends function’s execution and sends a value back to the caller, but retains enough state to enable function to resume where it is left off. When resumed, the function continues execution immediately after the last yield run. This allows its code to produce a series of values over time, rather than computing them at once and sending them back like a list.
Let’s see with an example:
1 2 3
Return sends a specified value back to its caller whereas Yield can produce a sequence of values. We should use yield when we want to iterate over a sequence, but don’t want to store the entire sequence in memory.
Yield are used in Python generators. A generator function is defined like a normal function, but whenever it needs to generate a value, it does so with the yield keyword rather than return. If the body of a def contains yield, the function automatically becomes a generator function.
1 4 9 16 25 36 49 64 81 100
This article is contributed by Arpit Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
- Difference between Yield and Return in Python
- Python | yield Keyword
- Python return statement
- Python | range() does not return an iterator
- Python | Return new list on element insertion
- Python | Return lowercase characters from given string
- Python | Ways to sum list of lists and return sum list
- Return the Index label if some condition is satisfied over a column in Pandas Dataframe
- Python - Read blob object in python using wand library
- Python | PRAW - Python Reddit API Wrapper
- twitter-text-python (ttp) module - Python
- MySQL-Connector-Python module in Python
- Python | Merge Python key values to list
- Python | Index of Non-Zero elements in Python list
- Python | Convert list to Python array
- Reading Python File-Like Objects from C | Python
- Important differences between Python 2.x and Python 3.x with examples
- Python | Add Logging to Python Libraries
- Python | Sort Python Dictionaries by Key or Value
- Python | Set 4 (Dictionary, Keywords in Python)
Improved By : julthep