Why can I use an iterator once but get nothing the second time?
Quick answer
An iterator supplies values as you retrieve them. Once exhausted, it does not rewind when you start another loop. A list is a reusable container: each loop over it can get a fresh iterator. To make two passes, keep the values in a list before consuming them, or create a fresh iterator from a source that can produce the values again.
The question, the details, the next step.
A practical checklist
Check whether both loops use the same iterator.
For two passes, keep the values in a list before consuming them.
If you can produce the values again, create a fresh iterator for each pass.
When converting an iterator to a list, remember it contains only values still available.
A few more useful answers
Does starting a new `for` loop rewind an iterator?
No. A new loop does not rewind the same exhausted iterator. Use a reusable container or create a fresh iterator from a source that can produce the values again. [S1]
Can I turn an exhausted iterator into a list to recover its original values?
No. Converting it to a list retrieves only values still available from that iterator. Make the list before consuming the values you need, or produce them again.
Is every iterable reusable like a list?
Do not assume so. A list produces a fresh iterator for each loop, but other objects may behave differently. [S1]
Sources
References used for this guide.
- [S1] Python Glossary: iterator and container docs.python.org · Checked
