2.next ( __next__ in Python 3) The iterator next method should return the next value for the iterable. When an iterator is used with a ‘for in’ loop, the for loop implicitly calls next() on the iterator object. This method should raise a StopIteration to signal the end of the iteration.
# working of iterators using an example type
# that iterates from 10 to given value
# An iterable user defined type
class Test:
def __init__(self, limit):
def __iter__(self):
# we should replace next with __next__
def next(self):
x = self.x
# Stop iteration if limit is reached
if x > self.limit:
self.x = x + 1;
return x
for i in Test(15):
for i in Test(5):
11
12
13
14
15