Generator and Iterators
Iterators And Generators¶
Iterables are objects that can return one of their elements at a time, such as a list. Many of the built-in functions we’ve used so far, like 'enumerate,' return an iterator.
An iterator is an object that represents a stream of data. This is different from a list, which is also an iterable, but is not an iterator because it is not a stream of data.
Generators are a simple way to create iterators using functions. You can also define iterators using classes, here documentation about it
Here is an example of a generator function called my_range, which produces an iterator that is a stream of numbers from 0 to (x - 1).
Notice that instead of using the return keyword, it uses yield. This allows the function to return values one at a time, and start where it left off each time it’s called. This yield keyword is what differentiates a generator from a typical function.
we can use the for loop to iterate over the iterator.
outputs:
Another example will be the implementation of the built-in function enumerate
having this:
We need to output:
so the code will be:
Chunker¶
If you have an iterable that is too large to fit in memory in full (e.g., when dealing with large files), being able to take and use chunks of it at a time can be very valuable.
Implement a generator function, chunker
, that takes in an iterable and yields a chunk of a specified size at a time.
Output:
Why Generators?¶
Generators are a lazy way to build iterables. They are useful when the fully realized list would not fit in memory, or when the cost to calculate each list element is high and you want to do it as late as possible. But they can only be iterated over once.
Generator Expressions¶
Here's a cool concept that combines generators and list comprehensions! You can actually create a generator in the same way you'd normally write a list comprehension, except with parentheses instead of square brackets. For example: