Generators are basically stateful functions. They can be paused and resumed at specific points.
Consider ordering fries, biryani, and ice cream at a restaurant. You could ask the waiter to get all the items in one go itself. However, it would be difficult to consume all of them in one sitting. Instead, you ask the waiter to get the first dish i.e fries, and once you are through with it, you could ask them to get the next one i.e biryani followed by ice cream.
Generators take a similar approach. A function is paused after it yields a value and resumes when it is explicitly asked.
Image Credits:
- <a href='https://www.freepik.com/photos/man-suit'>Man suit photo created by KamranAydinov - www.freepik.com</a>
- <a href='https://www.freepik.com/vectors/fries'>Fries vector created by brgfx - www.freepik.com</a>
- <a href="https://www.freepik.com/vectors/tasty-food">Tasty food vector created by freepik - www.freepik.com</a>
- <a href='https://www.freepik.com/vectors/brain-cartoon'>Brain cartoon vector created by catalyststuff - www.freepik.com</a>