Iterator function in Python



Explanation

Iterator is an object in python that implements iteration protocol. Tuples,lists,sets are called inbuilt iterators in Python.There are two types of method in iteration protocol.

__iter__() : This method is called when we initialize an iterator and this must return an object which consist next() or __next__()(in Python 3) method.

next() or __next__() (in Python 3) : This method should returns the next element from a iteration sequence.When an iterator is used with a for loop the for loop directly call the next() 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
      def __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
Samual Sam
Samual Sam

Learning faster. Every day.


Advertisements