[Python-ideas] Previous item from iterator.
Steven D'Aprano
steve at pearwood.info
Thu Apr 16 01:27:44 CEST 2015
On Wed, Apr 15, 2015 at 05:26:50PM +0100, Krystian Kichewko wrote:
> Hi all!
>
> I hope I'm posting in correct place.
>
> 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.
For experimentation purposes, you can easily write your own:
_sentinel = object()
def prev(it, default=_sentinel):
try:
return type(it).__prev__(it)
except StopIteration:
if default is _sentinel:
raise
else:
return _sentinel
ought to do it. Then you can write your own iterators, give them a
__prev__ method as well as a __next__ method, and experiment to see what
advantages it gives you (if any).
Can you demonstrate some useful tasks that are easier with this
bidirectional iteration than they currently are?
--
Steve
More information about the Python-ideas
mailing list