Search code examples
pythongeneratoryield

Resetting generator object in Python


I have a generator object returned by multiple yield. Preparation to call this generator is rather time-consuming operation. That is why I want to reuse the generator several times.

y = FunctionWithYield()
for x in y: print(x)
#here must be something to reset 'y'
for x in y: print(x)

Of course, I'm taking in mind copying content into simple list. Is there a way to reset my generator?


See also: How to look ahead one element (peek) in a Python generator?


Solution

  • Another option is to use the itertools.tee() function to create a second version of your generator:

    import itertools
    y = FunctionWithYield()
    y, y_backup = itertools.tee(y)
    for x in y:
        print(x)
    for x in y_backup:
        print(x)
    

    This could be beneficial from memory usage point of view if the original iteration might not process all the items.