To understand what yield does, let’s take an example.
Imagine a staircase. A staircase has steps, and climbing the stairs one by one until you reach the top is how you climb the staircase.
Taking many steps at a time is another approach to climbing the stairs. Depending on the length of your legs, you can take two, three, or even four steps at a time. The limitation here is the length of your legs. If the staircase is longer than your legs, you must climb it in parts.
And this limitation in programming is your computer's memory. How do you overcome this? Using Generator functions! Before going further, let’s know about Iterables and Iterators.
Python's sequence types (lists, tuples, and strings) and some container objects (dictionaries, sets, and file objects) behave similarly to staircases. These are known as iterables. Iterables are collections of values that may be counted and kept in memory.
Iterators are objects that implement the iterator protocol, which includes the methods __iter__() and __next__().
A generator function is a type of function that returns a lazy iterator known as a generator iterator. These are items that can be looped through like a list. Lazy iterators, unlike lists, do not retain their contents in memory. In Python, the yield keyword governs the flow of a generator function!
Want to know more about Python? Check out our blogs!