Iterator

  • Iterator is a python object that is used to iterate over iterable objects like lists, tuples, dicts, and sets.
  • It consist of the methods __iter__() and __next__().
  • __iter__method that is called for the initialization of an iterator. 
  • The __next__ method returns the next value for the iterable. 
  • The for loop actually creates an iterator object and executes the next() method for each loop.
mytup = (“revin", “reviving", “india")
myit = iter(mytup)

print(next(myit))
print(next(myit))
print(next(myit))
iter_obj = iter(iterable)

while True:

   try:

  element = next(iter_obj)

  except StopIteration:

  break

Create an Iterator

  • We need to implement the methods __iter__() and __next__() to your object.
  • The __iter__() method do operations related to initializing  and return iterator object
  • The __next__() method return the next item in the sequence
class MyNum:
  def __iter__(self):
    self.a = 1
    return self

  def __next__(self):
    x = self.a
    self.a += 1
    return x

obj1 = MyNum()
myiter = iter(obj1)
  • The previous example continue forever if you had enough next() statements.
  • To prevent the iteration to go on forever, we can use the StopIterationstatement.

Stop after 10 iterations

class MyNum:
  def __iter__(self):
    self.a = 1
    return self

  def __next__(self):
    if self.a <= 20:
      x = self.a
      self.a += 1
      return x
    else:
      raise StopIteration

obj1 = MyNum()
myiter = iter(obj1)

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *