Iterators: Would "rewind" be a good idea?

Heiko Wundram me+python at
Sun May 21 22:48:18 CEST 2006

Am Sonntag 21 Mai 2006 21:43 schrieb Charles D Hixson:
> I was reading through old messages in the list and came up against an
> idea that I thought might be of some value:
> "Wouldn't it be a good idea if one could "rewind" an iterator?"
> Not stated in precisely those terms, perhaps, but that's the way I read it.

Yes, that certainly would be a neat idea.

But, think of the following: what if the iterator computes the values at 
runtime, and you're not iterating over a "predefined" list of some sort? Do 
you want the machinery to store the state of the iterator at every earlier 
point in time (sometimes this may not even be possible, think of socket 
communication handled by iterators, or of some state being kept in a C 
extension outside of the grasp of the Python interpreter), and to restore the 
iterator to this point? Even if the generator you're trying to rewind can 
be "pickled" at each yield statement, memory requirements come to mind when 
thinking about this for the general case, where you simply don't want to 
rewind, but just iterate forward.

Anyway, an easy way out (if the aforementioned concerns don't apply) is always 
to create a list of the generator, and then to index that list directly:

x = list(gen())

A list can be freely indexed, so basically if you implement the iterator logic 
using a while loop, you're free to rewind as much as you'd like.

--- Heiko.

More information about the Python-list mailing list