Python Forum

Full Version: iterating an interator partially then resuming
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
i would like to iterate an iterator in a loop that will usually break out part way through. then later, i want another loop to resume that iteration from where the first one left off. how hard is this to do? what if there is a different need between these loops, perhaps in a function, to iterate that iterator from the beginning, maybe stopping at a different position? what seems like it would be useful is something that can make a stateful view of an iterator.
Iterators are objects, just like everything else:

>>> x = list(range(10))
>>> it = iter(x)
>>> for a in it:
...     print(a)
...     if a == 4:
...         break
...
0
1
2
3
4
>>> for b in it:
...     print(b)
...
5
6
7
8
9
However, I don't believe you can make iterators go backwards. You could recreate the iterator. You could also make a wrapper class for an iterator that keeps track of what was already iterated over in a stack, and then call it back somehow.
looks like exactly what i need. thanks!

the middle iteration can just run from the original or an iterator copy of the original.
looks like i have a case where the item i got from the iterator needs to be put back in the iterator so the 2nd loop processes that item again. this case is iterating over some command line arguments and breaking out when it hits a filename. then the 2nd loop finishes the filenames.

i also wonder if i could iterate nested. that is a deeper loop inside the outer loop with both loops iterating over the same iterator ... so the inner one can work on more than one item. but i'd still like to have the last item pushed back into/onto the iterator. i have been doing this in the past by make a list from the iterator then where needed, inserting items into the front of the list. but this all involved more code to handle details like popping items from a list inside a while True: loop.