Sometimes, we want to reset a generator object in Python.
In this article, we’ll look at how to reset a generator object in Python.
How to reset a generator object in Python?
To reset a generator object in Python, we can use the itertools.tee
method.
For instance, we write
import itertools
y = gen()
y, y_backup = itertools.tee(y)
for x in y:
print(x)
for x in y_backup:
print(x)
to call itertools.tee
with generator y
to get a 2nd version of the generator.
Then we get the original value returned from the y_backup
generator object.
Conclusion
To reset a generator object in Python, we can use the itertools.tee
method.