Python Iterators

Python Iterators: In Python, iterable objects include lists, tuples, sets, dictionaries, and strings, among others. These iterables can take on the form of an iterator, which implies that each element of the iterator can be retrieved using a loop statement. An iterator object in Python must implement the following methods:

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

 

Example:

The iterator MyIter is formed from the iterable MyList in the example below, and the next() function is used to get the iterator’s next element. Please notice that when the iterator has no more elements to iterate on, a StopIteration exception is thrown.

 

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

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

 

The output of the above code will be:

MON
TUE
WED

Loop over an Iterator

The for loop may also be used to iterate over the elements of any iterable.

 

Example:

A for loop is used to traverse over the iterable MyList in the example below.

 

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

for i in MyList:
  print(i)

 

The output of the above code will be:

MON
TUE
WED

Create an Iterator

In Python – Iterators, a user-defined iterator can be built, and the __iter__() and __next__() functions must be specified when doing so. The iterable object or class is initialised using the __iter__() function, and the __next__() method performs some process to return the next piece of the series.

 

Example:

In the example below, a MyIterClass iterator is generated, which starts with a square of one. The square of the next natural integer is the next element of this iterator.

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=" ")

 

The output of the above code will be:

1 4 9 16 25 36 49 64 81 100

Stop Iteration

To stop iteration at a certain moment, use the StopIteration statement. A termination condition can be created in the __next__() function to issue the StopIteration error. Consider the following example:

 

Example:

After reaching the square of 5, the iterator raises the StopIteration exception in the example below.

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))

 

The output of the above code will be:

1
4
9
16
25


Traceback (most recent call last):
  File "Main.py", line 19, in <module>
    print(next(MyIter))
  File "Main.py", line 13, in __next__
    raise StopIteration
StopIteration

 

Also Read: Java.lang package Tutorial

Leave a Reply

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