Generator functions are used to generate values on-demand, one at a time, which makes them memory-efficient and ideal for processing extensive or infinite datasets.
While generators excel at sequential data processing, they maintain an inherent state. Once a generator object is exhausted, iterating over it again produces no further values.
However, there are scenarios where reiterating over the same sequence becomes necessary, whether due to changing requirements or the need for multiple passes over the data. In such cases, resetting the generator object becomes crucial. In this article, we will see the different ways to reset the generator object in Python.
Recreating the generator object
The simplest way to reset a generator object is by recreating it. By calling the generator function or expression again, a fresh generator object is created, ready for a new iteration. Following is the example:
def countdown(n): while n > 0: yield n n -= 1 # Create the generator object countdown_gen = countdown(5) # Perform the initial iteration print("Initial iteration:") for num in countdown_gen: print(num, end=" ") # Output: 5 4 3 2 1 # Recreate the generator object countdown_gen = countdown(5) # Reset the iteration print("\n\nReset iteration:") for num in countdown_gen: print(num, end=" ") # Output: 5 4 3 2 1
Reset the generator using itertools.tee()
As an alternative way, we can also use the
itertools.tee() function to create multiple independent iterators from a single iterable. It is primarily used for creating independent streams but it can also be used to create a fresh iterator for a generator object.
Following is the example:
import itertools # Create the generator object countdown_gen = countdown(5) # Create a new iterator from the generator object iterator, _ = itertools.tee(countdown_gen) # Reset the iteration print("Reset iteration:") for num in iterator: print(num, end=" ") # Output: 5 4 3 2 1
In the above example, we used the
itertools.tee() to create a new iterator from the generator object and achieved a reset of the iteration without recreating the generator itself.