Reading Time: 1 minutes
Iterator Design Pattern in Python
Write a Python program to implement Iterator Design Pattern.
class CountTo: def __init__(self, upperBound): self.upperBound = upperBound self.numbersInEnglish = ["one", "two", "three", "four", "five", 'six', 'seven', 'eight', 'nine'] self.numbersInEnglish = self.numbersInEnglish[:upperBound] # trims the numbersInEnglish list to as many elements as the number supplied. self.index = 0 # index variable needed to keep track of the current position of the iterator in numbersInEnglish list. def __iter__(self): return self def __next__(self): try: result = self.numbersInEnglish[self.index] except IndexError: raise StopIteration self.index += 1 return result countTo3 = CountTo(3) print(next(countTo3)) print(next(countTo3)) print(next(countTo3)) ### OUTPUT ### one two three