Skip to content

Instantly share code, notes, and snippets.

@alexander-bauer
Last active September 16, 2021 20:03
Show Gist options
  • Save alexander-bauer/c8672550d6b98ed2ecad to your computer and use it in GitHub Desktop.
Save alexander-bauer/c8672550d6b98ed2ecad to your computer and use it in GitHub Desktop.
Peekable iterator wrapper in Python3
class Peekable():
"""An iterable class which can return the next element of the wrapped
iterator without advancing it."""
def __init__(self, iterator):
self.iterator = iterator
self.peeked = False
def peek(self):
if not self.peeked:
self.peeked = True
self.head = next(iterator)
return self.head
def __next__(self):
if self.peeked:
self.peeked = False
return self.head
else:
return next(iterator)
@mahmoudimus
Copy link

class Peekable(object):
    """An iterable class which can return the next element of the wrapped
    iterator without advancing it."""

    def __init__(self, iterator):
        self.head = None
        self.iterator = iterator
        self.peeked = False

    def peek(self):
        if not self.peeked:
            self.peeked = True
            self.head = next(self.iterator)
            return self.head

    def __next__(self):
        if self.peeked:
            self.peeked = False
            return self.head
        else:
            return next(self.iterator)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment