/    /  Python Iterators

Python iterators

As a part of OOPS Concepts, everything we mention is an Object even though it is a Variable or function endorsed in a Class. Similarly, Iterator is also an Object which has a collection of Iteration Values.

Iterator Objects return one value at a time till the Iteration Cycle Completes. Iterator object has two methods namely iter() and next() which will be collectively referred to as Iterator Protocol.

Python has in-built Iterator Objects such as List, tuple, dictionaries, Sets. Strings can also act as Iterator Containers to traverse across each character in a String. These are referred to as Iterable Containers from which Iterator gets derived from.

As mentioned above, We Can create our own Iterator Object using iter() and next() methods.

Let us see few examples on how Iterators can be used with in-built python objects.


Tuple:

mytuple = ("alex", "bravo", "charlie") #Declaring values as tuples
myit = iter(mytuple) # iter() method is used to traverse through Iterator
print(next(myit)) #next method helps us to traverse through tuple values
print(next(myit))
print(next(myit))


String:

mystr = "python"
myit = iter(mystr)
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))


Tuple with for loop:

mytuple = ("alex", "bravo", "charlie")
for x in mytuple:
  print(x)


String with for loop:

mystr = "python"
for x in mystr:
  print(x)


Creating our own Custom Iterator:

As metioned above, iter() and next() are methods which would be required to create Iterator Object.

As we are aware that init() method is used to initialize the functions and variables which have been created as a part of Class Creation. Similar to init() method iter() method does the same for Iterator Object which will return the iterator object itself.

next() method as mentioned above performs the same, it helps us to perform operations and returns the next item mentioned in the sequence.

Let us look at this with an example:

class MyIter:
  def __iter__(self):
    self.a = 1
    return self
  def __next__(self):
    x = self.a
    self.a += 1
    return x
myclass = MyIter()
myiter = iter(myclass)
print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))


Same can be implemented using for statement as:

class MyIter:
  def __iter__(self):
    self.a = 1
    return self
  def __next__(self):
    x = self.a
    self.a += 1
    return x
myclass = MyIter()
for x in myclass:
	print(x)


The above 2 programs can execute in an infinite loop we need a terminator to make sure it will not fall into Infinite Loop which can be achieved by invoking StopIteration statement in next() method.

Let us see the example.

class MyTest:
  def __iter__(self):
    self.a = 1
    return self
  def __next__(self):
    if self.a <= 15:
      x = self.a
      self.a += 1
      return x
    else:
      raise StopIteration
mytest = MyTest()
myiter = iter(mytest)
for x in myiter:
  print(x)