Is there an peekable similar to peekable but in additional allowing one to put some data to it?

Ian Kelly ian.g.kelly at
Wed Jan 11 12:07:35 EST 2017

On Wed, Jan 11, 2017 at 8:51 AM, Peng Yu <pengyu.ut at> wrote:
> Hi, peekable from more-itertools only allow peeking an iterator. But
> sometimes, one may want to take a look at an element, manipulate it,
> then put it back to the iterator. Is there a class in python that can
> help do this?

Not that I'm aware of, but maybe this recipe will help.

from collections import deque

class PushIterator:

    def __init__(self, iterable, push=()):
        self._iter = iter(iterable)
        self._pushed = deque(push)
        self._stopped = False

    def push(self, item):
        if self._stopped:
            raise RuntimeError('Cannot push onto exhausted iterator')

    def __iter__(self):
        return self

    def __next__(self):
        if self._pushed:
            return self._pushed.pop()
            return next(self._iter)
        except StopIteration:
            self._stopped = True

More information about the Python-list mailing list