Newby Coder header banner

Python Iterators

What is an iterator in Python?

Iterator in Python is simply an object that can be iterated upon, to retrieve each/any of its elements/items

Technically, iterator implements two methods, __iter__() and __next__()

Most of built-in containers in Python like:tuple, string sets etc. are iterables

These objects have a iter() method which is used to get an iterator

Iterating Through an Iterator in Python

The next() function can be used to manually iterate through the items of an iterator

When there is no more data to be returned, next() raises StopIteration

Example

Return an iterator from a tuple, and print each value:

nc_tuple = ("apple", "banana", "cherry")
nc_iter = iter(nc_tuple) print(next(nc_iter)) print(next(nc_iter)) print(next(nc_iter))

Example

Strings are also iterable objects, containing a sequence of characters:

nc_str = "bewine"
nc_iter = iter(nc_str) print(next(nc_iter)) print(next(nc_iter)) print(next(nc_iter)) print(next(nc_iter)) print(next(nc_iter)) print(next(nc_iter))

Iterating with for loop

for loop can be used to iterate over any object that can return an iterator, like list, string, file etc

>>>for item in [4, 7, 0, 3]:
...    print(item)
...
4
7
0
3 
The for loop can iterate over any iterable

Custom Iterator in Python

To build an iterator the methods __iter__() and __next__() have to be implemented

The __iter__() method is to return the iterator object itself, with any required initialization

The __next__() method is to return the next item in the sequence, such that it raises StopIteration on reaching end of sequence

Following example gets the next power of 3 in each iteration

import math

class PowThree:
    def __init__(self, n):
        self.n = n

    def __iter__(self):
        self.a = 0
        return self

    def __next__(self):
        if self.a > self.n:
            raise StopIteration
        self.a += 1
        return math.pow(3, self.a)

nc_class = PowThree(4)
nc_iter = iter(nc_class)
print(next(nc_iter))
print(next(nc_iter))
print(next(nc_iter))
print(next(nc_iter))
print(next(nc_iter)) 

Power exponent starts from zero up to a number set by user

1.0
3.0
9.0
27.0
81.0
Traceback(most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 10, in __next__
StopIteration 

A for loop can be used to iterate over iterator class

>>>for i in PowThree(5):
...    print(i)
...
1.0
3.0
9.0
27.0
81.0
243.0 

StopIteration

StopIteration statement is used inside __next__() method to stop an iteration based on some condition

Example

Stop after 20 iterations:

class NcNumbers:

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

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

nc_class = NcNumbers()
nc_iter = iter(nc_class)
for x in myiter:
  print(x)