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 firstname.lastname@example.org. 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
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.
- Difference between Yield and Return in Python
- Python | yield Keyword
- Use of nonlocal vs use of global keyword in Python
- Python | Return new list on element insertion
- Python | range() does not return an iterator
- Python | Ways to sum list of lists and return sum list
- Python | Return lowercase characters from given string
- Python return statement
- Python Program to Return the Length of the Longest Word from the List of Words
- Return the Index label if some condition is satisfied over a column in Pandas Dataframe
- PyQt5 QDateTimeEdit – Signal when return key is pressed
- Return multiple columns using Pandas apply() method
- Python | Use of __slots__
- How to use a List as a key of a Dictionary in Python 3?
- Use Pandas to Calculate Statistics in Python
- Use of min() and max() in Python
- Python | How to use Multiple kv files in kivy
- How to use multiple UX Widgets in kivy | Python
- Use of slice() in Python
- How to use sys.argv in Python
Improved By : julthep