The Python Tutorial - 9.8. Iterators

Hi. The Python Tutorial 9.8. Iterators class Reverse: """Iterator for looping over a sequence backwards.""" def __init__(self, data): self.data = data self.index = len(data) def __iter__(self): return self def __next__(self): if self.index == 0: raise StopIteration self.index = self.index - 1 return self.data[self.index] this example not reusable but def __iter__(self): self.index = len(self.data) return self made it reusabled -- Best regards, Aleksandr Shevchenko

Hi, thanks for your message! I'm not sure it's worth it, I mean, if we want a nice Reverse, let's not just enhance a single step, let's allow for a same reverse to be iterated by multiple iterators in the same time, this mean implementing a ReverseIterator keeping track of the current position. But let's keep the Tutorial simple. I'll be OK though to add a line *after* the example, right before 9.9, telling that this example is basic and could be enhanced by returning a dedicated ReverseIterator instead of returning self, so every one could track the position. If you want to open a PR on http://github.com/python/cpython/ to add this sentense I'll happily merge it. Bests, -- Julien Palard https://mdk.fr
participants (2)
-
Aleksandr Shevchenko
-
Julien Palard