Skip to content

Instantly share code, notes, and snippets.

@ajarmst
Created March 8, 2022 23:10
Show Gist options
  • Save ajarmst/41ab27f68fd7cf265d41ffc7a664a61f to your computer and use it in GitHub Desktop.
Save ajarmst/41ab27f68fd7cf265d41ffc7a664a61f to your computer and use it in GitHub Desktop.
class Reverse:
"""Creates an iterator that reverses the object constructed"""
def __init__(self, data):
"""Usual constructor. Note that in this case, we need to have
a member variable that will maintain my state when implementing
__next__for iteration."""
self.data = data # Some iterable set of data
self.index = len(data) # data better support the len operation
def __iter__(self):
"""If an object is passed to for, whatever __iter__ returns
is what will be used. That returned object must have a
__next__ method"""
return self # The class already has __next__, so good to go
def __next__(self):
"""Implement the iteration behavior, including throwing an
exception when we're done"""
if self.index == 0: #Remember, going backward, so this is the last
raise StopIteration
self.index = self.index - 1 # Update state
return self.data[self.index] # Return the latest iterated value from data
if __name__ == '__main__':
for c in Reverse('Welcome to PyCharm'):
print(c, end='')
print()
# See PyCharm help at https://www.jetbrains.com/help/pycharm/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment