Python
generator
programming
reset generator
code tutorial

How to reset a generator object in Python

Codemia Knowledge Hub ·

You cannot reset a Python generator object back to the beginning. A generator is stateful: once it advances, its execution state moves forward until it is exhausted. For restartable iteration, create a new generator object, or wrap the logic in an iterable that produces a fresh generator each time.

Why generators cannot be rewound

A generator remembers its current execution point, local variables, and pending yield position, and Python has no API to rewind that state.

python
1def numbers():
2    yield 1
3    yield 2
4    yield 3
5
6g = numbers()
7print(next(g))
8print(next(g))

Here g is already partway through the function. There is no reset() method to send it back to the first yield.

Call the generator function again

The normal "reset" is to call the generator function again.

python
1def numbers():
2    yield 1
3    yield 2
4    yield 3
5
6g = numbers()
7print(list(g))
8
9g = numbers()  # fresh generator
10print(list(g))

Generator functions are factories for generator objects. The function stays reusable even though each generator instance is single-pass.

Return a fresh generator from __iter__

If callers should be able to iterate repeatedly without recreating anything, use a class whose __iter__ returns a new generator.

python
1class Countdown:
2    def __init__(self, start):
3        self.start = start
4
5    def __iter__(self):
6        for n in range(self.start, 0, -1):
7            yield n
8
9values = Countdown(3)
10print(list(values))
11print(list(values))

The object is reusable because each iteration gets a fresh generator. The same idea applies if you store a generator as an object attribute and expect every method call to start from the beginning: store the generator function or the source data instead.

Cache the values when you need replay

If the computation is expensive and the result is finite, the right answer may be to store the generated values rather than reset anything.

python
1def squares():
2    for n in range(5):
3        yield n * n
4
5cached = list(squares())
6print(cached)
7print(cached)

This trades memory for replayability. It fits when the sequence is small or repeated access matters more than streaming; materializing an enormous generator into a list can cost a lot of memory.

itertools.tee does not rewind

itertools.tee splits one iterator into several independent iterators, but it is not a reset.

python
1import itertools
2
3def letters():
4    for ch in "abc":
5        yield ch
6
7g1, g2 = itertools.tee(letters(), 2)
8print(next(g1))
9print(list(g2))

It duplicates iteration state forward from the current point. It cannot take an already-consumed generator back to the start.

Picking the right abstraction

Decide what you actually need:

  1. single-pass streaming
  2. repeatable iteration
  3. cached results for reuse

If repeatability is required, a bare generator object is usually the wrong thing to hand around. This matters most in APIs: returning a generator is ideal for streaming, but it surprises callers who assume they can iterate the result multiple times like a list.


Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Basis Lab
No course covers this one yet

Basis Lab writes one for you from a sentence about what you want to be able to do, then teaches it and checks you understood. Your first course is free.

Build my course
Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms