Iterators in Python

An Iterator is a Python object which is capable of iterating over a sequence [list, tuple, set etc]. To iterate means to traverse all the items of a sequence one by one in an order.

Iterables are those objects which can be iterated, therefore List, Tuples, Set etc are iterables. Every iterable creates an object to perform iteration over itself. This object is iterator.

Most of the significant concepts of python programming like for loops, comprehensions etc, use Iterators but they are not visible to the programmer.

Iterators use an Iterator Protocol which implements two methods namely iter() & next().

iter(): This method takes the iterable as the parameter and it calls a function __iter__(). This functions creates an iterator & returns it.

Syntax:
iterator_name = iter(iterable)

next(): This method takes the iterator as the parameter and calls __next__() function. This function finds out the next element present in the iterable and returns it.

In addition, this method raises an exception StopIteration when no more elements are left in the iterable to be traversed.

Syntax:
next(iterator_name)

Example:

My_num = [10,20,30,40,50] #creating an iterable i.e a list
My_iterator = iter(My_num) #creating an iterator for the list

#printing the next elements one by one with next() method.
print( next(My_iterator))
print( next(My_iterator))
print( next(My_iterator))
print( next(My_iterator))
print( next(My_iterator))
print( next(My_iterator))

Output:

10
20
30
40
50
Traceback (most recent call last):
File "C:/Users/TS7/AppData/Local/Programs/Python/Python37/iterator.py", line 9, in <module>
print(next(My_iterator))
StopIteration

Explanation:

  • In this program, a list My_num is created for which an iterator is created using the iter() method. The iter() method takes the iterable (List, in this case) as the parameter. The iterator returned by iter() method is assigned to a variable named My_iterator.
  • In the next step, next() method is used to call the next elements of the iterable starting with the first one. Simultaneously, the print statement displays the traversed elements in the output.
  • After visiting the last element of the list, the next() method raises StopIteration exception and indicates that the iterable has no more elements to be traversed.

How to create an iterator yourself?

You can create your own iterators with the help of __iter__() and __next__() method.

Example:

class Rainbow:
   def __init__(self):
      self.color = ['Violet','Indigo','Blue','Green','Yellow','Orange','Red']
      self.i = -1

   def __iter__(self):
      return self

   def __next__(self):
      self.i += 1
      if self.i == len(self.color):
         raise StopIteration
      else:
         return self.color[self.i]

col = Rainbow() #creating object of the class
My_iterator = iter(col) #creating the iterator

print(next(My_iterator))
print(next(My_iterator))
print(next(My_iterator))
print(next(My_iterator))
print(next(My_iterator))
print(next(My_iterator))
print(next(My_iterator))

Output:

Violet
Indigo
Blue
Green
Yellow
Orange
Red

Explanation:

  • In this program, a class named Rainbow is created. We have used __init__() method to create the attributes of the class, namely, a list color & an integer i.
  • Another method __iter__() is used for the purpose of initialization and __next__() method is used to return the next element of the iterable.
  • An if statement is implemented which raises an exception if the value of i goes beyond the length of the list.
  • The else part of the statement uses __next__() method to access the elements of the list one after the other till the last element.

How does Python For Loop work?

As you have seen, the For loop in Python is much shorter and simpler than other languages. But the actual working of the for loop is a little complex inside. If you are not aware of what the Python for loop is. You may first have a look at our article Python For Loop.

For loop is used to iterate over an iterable in Python. It works on the basis of Iterators.

As an iterable is given to the for loop, an iterator object is created using iter() method. This iterator is passed to the next() method to fetch the next element present in the iterable.
A condition is set such that an exception is raised when there are no more elements left in the iterable.