Computer >> Computer tutorials >  >> Programming >> Python

Python Iterator Types


In python there is iteration concepts over containers. Iterators have two distinct functions. Using these functions, we can use user defined classes to support iteration. These functions are __iter__() and the __next__().

Method __iter__()

The __iter__() method returns iterator object. If one class supports different types of iteration, then some other methods can be there to do some other tasks.

Method __next__()

The __next__() method returns the next element from the container. When the item is finished, it will raise the StopIteration exception.

Example Code

class PowerIter:
   #It will return x ^ x where x is in range 1 to max
   def __init__(self, max = 0):
      self.max = max #Set the max limit of the iterator
        
   def __iter__(self):
      self.term = 0
      return self
    
   def __next__(self):
      if self.term <= self.max:
         element = self.term ** self.term
         self.term += 1
         return element
      else:
         raise StopIteration #When it exceeds the max, return exception
powIterObj = PowerIter(10)
powIter = iter(powIterObj)
for i in range(10):
   print(next(powIter))

Output

1
1
4
27
256
3125
46656
823543
16777216
387420489