Custom iterator class

MediumIterator & Generator Programs · 7 of 20

Write an iterator class that returns the characters of a word in reverse.

Advertisement
Output
nohtyp

Approach

  1. Implement __iter__ and __next__.

Solution

Python
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.

More iterator & generator programs

← All 20 Iterator & Generator Programs

Leave a Comment