[Python-ideas] Previous item from iterator.
Cameron Simpson
cs at zip.com.au
Thu Apr 16 02:22:50 CEST 2015
On 15Apr2015 17:26, Krystian Kichewko <krystiankichewko at gmail.com> wrote:
>I would like to propose an idea for iterating over an iterator in reverse.
>
>prev(iterator[, default])
>
>Built-in function: it should retrieve previous element from an
>iterator by calling its __prev__() method.
>
>Add new, optional method to iterator protocol:
>
>__prev__()
>
>This method should return previous element from iterator or raise
>StopIteration exception if the is no previous element.
In addition to the existing responses (working prototype from Steven, various
discussions around lists and dicts), my own suggestion would be an itertools
wrapper like this:
from itertools import rewindable
it = original_iterator
bi_dir_it = rewindable(it)
where "rewindable" returned an iterator that recorded the values issued by an n
existing iterator, probably with an optional upper limit. Then all the
rewindable object needs to do is stash values in a list as they are returned,
and keep an offset into the stash to implement prev and next.
i.e. instead of bulking up the iterator protocol, provide a helper wrapper.
That way any iterator can be used with your proposal.
Cheers,
Cameron Simpson <cs at zip.com.au>
It's better, when you're racing with someone you don't know so well,
to stick to the inside line - it's easier to avoid the bits.
- Barry Sheene, bike GP commentator
More information about the Python-ideas
mailing list