python peek next item from iterator

Solutions on MaxInterview for python peek next item from iterator by the best coders in the world

showing results for - "python peek next item from iterator"
Emily
08 Aug 2017
1class Peekorator(object):
2
3    def __init__(self, generator):
4        self.empty = False
5        self.peek = None
6        self.generator = generator
7        try:
8            self.peek = self.generator.next()
9        except StopIteration:
10            self.empty = True
11
12    def __iter__(self):
13        return self
14
15    def next(self):
16        """
17        Return the self.peek element, or raise StopIteration
18        if empty
19        """
20        if self.empty:
21            raise StopIteration()
22        to_return = self.peek
23        try:
24            self.peek = self.generator.next()
25        except StopIteration:
26            self.peek = None
27            self.empty = True
28        return to_return
29
30def simple_iterator():
31    for x in range(10):
32        yield x*3
33
34pkr = Peekorator(simple_iterator())
35for i in pkr:
36    print i, pkr.peek, pkr.empty