Question:
Write a iterator function to work like xrange()
Program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
class yrange: def __init__(self, n): self.i = 0 self.n = n def __iter__(self): return self def next(self): if self.i < self.n: i = self.i self.i += 1 return i else: raise StopIteration() print list(yrange(input("Enter the number:"))) |
Explanation:
The iterator protocol consists of two methods. The __iter__() method, which must return the iterator object and the next() method, which returns the next element from a sequence. Python has several built-in objects, which implement the iterator protocol. For example lists, tuples, strings, dictionaries or files.
Output:
1 2 |
Enter the number:3 [0, 1, 2] |
Leave a Reply