BETTER PROGRAMMING
How to Use Generator and yield in Python
Work with large datasets or files using Python generators
Today we are going to talk about generators in Python, how are they different from normal functions, and why you should use them.
What are generators in Python?
Have you ever run into a situation where you would need to read large datasets or files, and those were too overwhelming to load into memory? Or maybe you wanted to build an iterator, but the producer function was so simple that most of your code is just around building the iterator other than producing the desired values? These are some of the scenarios where generator can be really useful and simple.
Introduced with PEP 255, generator functions are a special kind of function that returns some sort of lazy iterator. There are objects that you can loop over like a list, however, unlike lists, lazy iterators do not store their contents in memory. One of the advantages of generator functions to iterators is the amount of code that is required to code.
After that introduction, let’s see some examples of generators in action: