python


Python Iterators


An iterator may be defined as an object that contains countable number of values.
In other words an iteratoris an object through which we can traverse all the given values.
In python, techically an iterator is an object which consists of __iter__() and __next__() methods.

The iter() method

As we know, list,tuples,dictionaries,sets are iterable objects.All these objects have their iter() method which is used to get an iterator.
Lwt's take an example of a list.

Example:
list1 = ["january", "february", "march"]
iterator1 = iter(list1)

print(next(iterator1))
print(next(iterator1))
print(next(iterator1))
Output:
january
february
march

In the above code, we create a list named list1 in which we used iter() method to access all the elements.

Note:Strings are also iterable objects.It will work same as list worked above.

Using loop through an Iterator

We can also use loop to iterate through the iterable objects.
For example,take for loop in to iterate through objects.

Example:
list1 = ["january", "february", "march"]
for var in list1:
    print(var)
Output:
january
february
march

We can also use loops in tuple,dictionaries ,sets as well as strings.

Creation of Iterators

For craetion of an bject/class as an iterator, we have to use 2 methods here:

  1. __iter__()
  2. __next__()

The above methods should be implemented to the objects.

__iter__() method- This method is helps us to perform the operations but it will always return the iterator object itself.


__next__() method- This method allows us to do operations and it will return the next item in the sequence.


Example:
class Multiple:
  def __iter__(self):
    self.num = 10
    return self

  def __next__(self):
    var = self.num
    self.num *= 10
    return var

nclass = Multiple()
iterator = iter(nclass)

print(next(iterator))
print(next(iterator))
print(next(iterator))
print(next(iterator))
print(next(iterator))
Output:
10
100
1000
10000
100000
StopIteration statement

This statement is used to stop the iteration at a particular condition. It will prevent the iteration to go on forever.
In the __next__() method, we can add a terminating condition to raise an error if the iteration is done a specified number of times.

Syntax:
def __next__(self):
if condition:
    code
else:
    raise StopIteration  #The raise keyword is used to raise an exception.
Example:
class Multiple:
  def __iter__(self):
    self.num = 10
    return self

  def __next__(self):
    if self.num <=100000:       #condition
      var = self.num
      self.num *= 10
      return var
    else:
      raise StopIteration

numclass = Multiple()
iterator = iter(numclass)

for var in iterator:
  print(var)
Output:
10
100
1000
10000
100000
1000000

In the above code, we used the statement StopIteration to prevent our loop to run forever.