Python Practice › Iterator & Generator Programs › Program 7
Custom iterator class
Write an iterator class that returns the characters of a word in reverse.
Output
nohtyp
Approach
- Implement
__iter__and__next__.
Solution
class Reverse: def __init__(self, text): self.text = text self.index = len(text) def __iter__(self): return self def __next__(self): if self.index == 0: raise StopIteration self.index -= 1 return self.text[self.index] print("".join(Reverse("python")))Output
nohtyp
Learn the concept
New to this topic? Read the lesson, then come back.