Contents
Iterator &it is an object in Python that implements the iteration protocol. Tuples, lists, sets are called built-in iterators in Python. There are two types of methods in the iteration protocol.
__iter __ (): This method is called when we initialize the iterator and it should return an object consisting of a next () or __next __ () method (in Python 3).
next () or __next __ () (in Python 3): This method should return the next element from the iteration sequence. When an iterator is used with a for loop, the for loop calls next () directly on the iterator object.
Example code
# creating a custom iterator class Pow_of_Two: def __init __ (self, max = 0): self.max = max def __iter __ (self) : self.n = 0 return self de f __next __ (self): if self.n "= self.max: result = 2 ** self.n self.n + = 1 return result else: raise StopIteration ("Message") a = Pow_of_Two (4) i = iter (a) print (i .__ next __ ()) print (next (i)) print (next (i)) print (next (i)) print (next (i)) print (next (i))
Output
1 2 4 8 16 StopIteration error will be raised