Python - Iterators

Python - Iterators


Previous Page

There are various iterable objects in Python like lists, tuples, sets, dictionaries, and strings, etc. These iterables can get iterator form which means that an iterator can be iterated upon and each elements of the iterator can be accessed using a loop statement. In Python, an iterator object must implement following methods:

  • __iter__(): to initialize an iterator.
  • __next__(): to perform operations for next element and return next element of the iterator.

Example:

In the below example, an iterator called MyIter is created from the iterable called MyList and after that next() method is used to access next element of the iterator. Please note that, a StopIteration exception is raised when the iterator do not have more elements to iterate upon.

MyList = ['MON', 'TUE', 'WED']
MyIter = iter(MyList)

print(next(MyIter))
print(next(MyIter))
print(next(MyIter))

Output

MON
TUE
WED

Loop over an Iterator

The for loop can also be used with any iterable to iterate over the elements of it.

Example:

In the below example, a for loop is used to iterate over the iterable called MyList.

MyList = ['MON', 'TUE', 'WED']

for i in MyList:
  print(i)

Output

MON
TUE
WED

Create an Iterator

A user-defined iterator can be created in Python and it is must to define __iter__() and __next__() methods while creating it. The __iter__() method is used to initialize the iterable object or class and the __next__() method is used to perform some operation to return next element of the sequence.

Example:

In the below example, an iterator called MyIterClass is created which initiates with square of 1. The next element of this iterator is the square of the next natural number.

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

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

IterObj = MyIterClass()
MyIter = iter(IterObj)

for i in range(1, 11):
  print(next(MyIter), end=" ")

Output

1 4 9 16 25 36 49 64 81 100

StopIteration

The StopIteration statement can be used to stop iteration at desired point. In the __next__() method, a terminating condition can be created to raise StopIteration error. Please see the example below:

Example:

In the below example, the iterator raises StopIteration exception after reaching square of 5.

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

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

IterObj = MyIterClass()
MyIter = iter(IterObj)

for i in range(1, 11):
  print(next(MyIter))

Output

1
4
9
16
25
Error!
StopIteration

Previous Page