Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
Python interview question
Iterators, generators & decoratorsMiddleCommonTroubleshooting

Why does iterating a generator a second time produce no items, and how do you work around that?

Answer

A generator holds its execution state internally and is exhausted the moment it raises `StopIteration`; there is no built-in way to "rewind" it, so a second `for` loop or `list()` call over the same generator object simply produces nothing. Unlike a list, a generator is not reusable. The workaround is to call the generator function again to get a fresh generator object, or to materialize the values into a list once if you genuinely need to iterate them more than once, accepting the memory cost of doing so.

Strong answer includes

  • a generator is exhausted after raising StopIteration once, no rewind
  • a second pass over the same generator object yields nothing
  • workaround: call the generator function again, or materialize into a list

Practical example

A generator is single-use
Python
editable · browser sandbox
Result
Run the code to see the result.

Once a generator reaches StopIteration it stays exhausted. Re-run the generator function to get a fresh generator when you need another pass.

Expected result: [1, 2], then [], then [1, 2].

#generators#gotchas

Sources

The Python Language ReferencePython Software Foundation · Precise scoping, evaluation order and expression semantics