Design Pattern: Introduction to Python Iterator Pattern

Avijit Biswas
4 min readMar 28, 2023
A potter making clay pot of a certain design.
Photo by Quino Al on Unsplash

Introduction

We live in a world where design is everywhere. You may be reading this article on a Phone, tablet, laptop, or MacBook which has a certain design. This particular design solves a particular problem, if one phone solves all the problems then there is no requirement for tablets, Macbooks, or PC.

A particular item has a specific design.

Also, you can think of a potter who is making clay items such as cups, flower vases, and many more such things which are used for a specific type of need. A particular item has a specific design. Design patterns in software engineering aim to provide a formal definition of correctly designed software structures. In this article, we will discuss the very important Iterator Pattern in Python.

What is Iterator mean?

In computer programming, an iterator is an object that enables a programmer to traverse a container, particularly lists.

The above definition is from Wikipedia, which actually tells that if you can use for loop or while loop on any container class such as list, array, set, tuple, or dictionary then it must have an iteration logic implemented in it.

see the below example,

items = [1,2,3,4,5]
for i in range(len(items)):
print(items[i])

>>>
1
2
3
4
5

That means we iterate through the list of objects named as items and print the outputs.

You can find iterators in almost all languages. In Python, the method gets a special name, __next__. This method can be accessed using the next(iterattor) builtin.

When the iterator is completed, Python’s iterator protocol raises the StopIteration exception to tell the client that it has been completed.

Iterator Protocol

The collections.abc module consists Iteratorabstract base class which defines the iterator protocol in Python.

Any collection class definition must be Iterable.

Any collection class definition must be Iterable. But what does it mean? It means the collection class must implement an __iter__() method, this method creates an Iterator object.

Author
Photo by Author

In the above image, you can show that the Collection class has three methods.

  • __contains__()
  • __iter__()
  • __len__()

The collection class implements the __iter__() method from Iterable. and to become Iterable have Iterator which has two method

  • __next__()
  • __iter__()
Photo by author

The iterator class must define __Iter__() this will ensure that the for statement or thewhile statement can get new elements from the list or sequence.

Now, clear the rest of the confusion by creating an example of it.

We will create an Iterable class which will Square the element from the list.

import math as m
from typing import Iterable, Iterator

class SquareIterable:
def __init__(self, arr: list) -> None:
self.arr = arr

def __iter__(self) -> Iterator[int]:
return SquareIterator(self.arr)

class SquareIterator(Iterator[int]):
def __init__(self, arr) -> None:
self.items = [(x**2) for x in arr]
self.index = 0

def __next__(self) -> int:
if self.index == len(self.items):
raise StopIteration()
item = self.items[self.index]
self.index += 1
return item

There are two class

  • SquareIterable: This class is the Iterable class which returns an iterator. This class initialize with a list and implements __iter__() methods.
Photo by author
  • SquareIterator: This class actually creates the iterator object which will return by the SquareIterable Object in the run time. The main squaring logic is implemented in the __init__() method and the __next__() method implements the Iterator logic.
Photo by author

Let’s understand the __next__() method

  • when the index of the list will equal the length of the list it will raise StopIteration()
  • Otherwise, it fetches the item from the list with the index.
  • and then increase the index by 1.
  • At the last, it returns the item.

Run an example as below,

if __name__ =="__main__":
arr = [1,2,3,4,5,6,7,8]
iterable = SquareIterable(arr)
iterator = iter(iterable)
while True:
try:
print(next(iterator))
except StopIteration:
break
>>>
1
4
9
16
25
36
49
64

Conclusion

Iterator is everywhere in the programming world without them there was no list comprehension, for looping or while looping on list, tuples, sets, and dictionary.

In this article, I discuss iterators in a beginner-friendly way. You can use this same pattern to make your Iteartor easily.

I hope this post helps you.

Thanks for reading, friend! If you enjoyed my article, let’s keep in touch on LinkedIn, Twitter, and Medium.

--

--