"Backward"-Iterator - Beginners question

Terry Reedy tjreedy at udel.edu
Thu Oct 31 18:35:03 EDT 2013


On 10/31/2013 5:29 PM, Ulrich Goebel wrote:

> I'm locking for an "iterator" type with not only the .next() method, but
> with a .previous(), .first() and .last() method, so that I can through
> it from the beginning or from the end, and in both directions, even
> alternately (for example two steps forward, one backward, two steps
> forward).

You are free to write such a class, if it is appropriate for your actual 
use case.

If you have a concrete sequence object seq with random access, there is 
no reason to do so. First and last are seq[0] and seq[-1]. Given 
'cursor' i, prev and next are 'i-=1;seq[i]' and 'i+=1;seq[i]'.

There *are* virtual sequences where first and last are known or 
relatively easy to compute and for which prev and next are much easier 
to compute than a random nth item. Note that if you start with first and 
mostly move forward, prev might best be implemented using a list of 
items already seen. The list and the prev function might be limited to 
the last N items seen. It you give up the last function, the underlying 
sequence does not even have to have a definite end.

A somewhat realistic (useful) example might be the following. You have a 
very long sequence of bytes that represent utf-8 encoded characters. You 
want to view the sequence as a sequence of sentences. The sequence is 
too long to simply create a list of (decoded) sentences in memory.

-- 
Terry Jan Reedy




More information about the Python-list mailing list