Open In App

Iterator Method – Python Design Patterns

Last Updated : 29 May, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

Iterator method is a Behavioral Design Pattern that allows us to traverse the elements of the collections without taking the exposure of in-depth details of the elements. It provides a way to access the elements of complex data structure sequentially without repeating them.
According to GangOfFour, Iterator Pattern is used ” to access the elements of an aggregate object sequentially without exposing its underlying implementation”.
 

The following diagram depicts the Linked List data structure. 
 

Iterator-Method-Linked-List

Iterator-method-Linked-List

 

Problem Without using Iterator Method

Imagine you are creating an application for small kids which takes any valid alphabet as input and return all the alphabets up to that. When this application will be used only a few times, it is okay to run For loop and While loop again and again but when the frequency of running increases this process becomes quite inefficient. So, we have to find a way in order to avoid these loops. This problem may become bigger when we will work on complex non-linear data structures like Trees, Graphs where traversing is not that simple as in an array. 
The following diagram depicts the image of the Tree data structure.
 

Iterator-Method-Tree-Data-Structure

Iterator-Method-Tree-Data-Structure

 

Solution Using Iterator Method

Here we will discuss the solution for the above-described problem. It’s always handy for Python users to use Iterators for traversing any kind of data structure doesn’t matter they are linear or no-linear data structures. We have two options to implement Iterators in Python either we can use the in-built iterators to produce the fruitful output or explicitly we can create iterators with the help of Generators. In the following code, we have explicitly created the Iterators with the help of generators.
 

Note: Following code is the example of an explicitly created Iterator method
 

Python3




""" helper method for iterator"""
 
 
def alphabets_upto(letter):
    """Counts by word numbers, up to a maximum of five"""
    for i in range(65, ord(letter)+1):
            yield chr(i)
 
 
"""main method"""
if __name__ == "__main__":
 
    alphabets_upto_K = alphabets_upto('K')
    alphabets_upto_M = alphabets_upto('M')
 
    for alpha in alphabets_upto_K:
        print(alpha, end=" ")
 
    print()
 
    for alpha in alphabets_upto_M:
        print(alpha, end=" ")


Note: Following code is the example of using an in-built iterator method
 

Python3




"""utility function"""
def inBuilt_Iterator1():
     
    alphabets = [chr(i) for i in range(65, 91)]
     
    """using in-built iterator"""
    for alpha in alphabets:
        print(alpha, end = " ")
    print()
 
"""utility function"""
def inBuilt_Iterator2():
     
    alphabets = [chr(i) for i in range(97, 123)]
     
    """using in-built iterator"""
    for alpha in alphabets:
        print(alpha, end = " ")
    print()
 
 
"""main method"""
if __name__ == "__main__" :
     
    """call the inbuiltIterators"""
    inBuilt_Iterator1()
    inBuilt_Iterator2()


Class Diagram

Following is the class diagram for the Iterator Method 
 

Iterator-Method-Class-Diagram

Iterator-Method-Class-Diagram

 

Advantages

  • Single Responsibility Principle: It’s really easy to extract the huge algorithms into separate classes in the Iterator method.
  • Open/Closed Principle: Passing the new iterators and collections into the client code does not break the code can easily be installed into it.
  • Easy to use Interface: It makes the interface really simple to use and also supports the variations in the traversal of the collections.

 

Disadvantages

  • Unnecessary Wasting resources: It’s not always a good habit to use the Iterator Method because sometimes it may prove as an overkill of resources in a simple application where complex things are not required.
  • Increases Complexity: As we said earlier, using the Iterator method makes simple applications complex.
  • Decreases Efficiency: Accessing elements directly is a much better option as compared to accessing elements using the iterator in terms of efficiency.

 

Applicability
 

  • Limited Exposure: When you want to access the elements at the lower level i.e., you are not interested in the internal implementation of the elements then it’s always preferred to use the Iterator Method.
  • Traversing Unknown Data Structures: The iterator method can be easily used to traverse various types of data structures such as Trees, Graphs, Stack, Queue, etc. as the code provides a couple of generic interfaces for both collections and iterators.

Further Read – Iterator Method in Java
 



Previous Article
Next Article

Similar Reads

Template Method - Python Design Patterns
The Template method is a Behavioral Design Pattern that defines the skeleton of the operation and leaves the details to be implemented by the child class. Its subclasses can override the method implementations as per need but the invocation is to be in the same way as defined by an abstract class. It is one of the easiest among the Behavioral desig
4 min read
Factory Method - Python Design Patterns
Factory Method is a Creational Design Pattern that allows an interface or a class to create an object, but lets subclasses decide which class or object to instantiate. Using the Factory method, we have the best ways to create an object. Here, objects are created without exposing the logic to the client, and for creating the new type of object, the
5 min read
Abstract Factory Method - Python Design Patterns
Abstract Factory Method is a Creational Design pattern that allows you to produce the families of related objects without specifying their concrete classes. Using the abstract factory method, we have the easiest ways to produce a similar type of many objects. It provides a way to encapsulate a group of individual factories. Basically, here we try t
4 min read
Singleton Method - Python Design Patterns
Prerequisite: Singleton Design pattern | Introduction What is Singleton Method in PythonSingleton Method is a type of Creational Design pattern and is one of the simplest design patterns available to us. It is a way to provide one and only one object of a particular type. It involves only one class to create methods and specify the objects. Singlet
5 min read
Prototype Method - Python Design Patterns
Prototype Method is a Creational Design Pattern which aims to reduce the number of classes used for an application. It allows you to copy existing objects independent of the concrete implementation of their classes. Generally, here the object is created by copying a prototypical instance during run-time. It is highly recommended to use Prototype Me
5 min read
Builder Method - Python Design Patterns
Builder Method is a Creation Design Pattern which aims to "Separate the construction of a complex object from its representation so that the same construction process can create different representations." It allows you to construct complex objects step by step. Here using the same construction code, we can produce different types and representatio
5 min read
Adapter Method - Python Design Patterns
Adapter method is a Structural Design Pattern which helps us in making the incompatible objects adaptable to each other. The Adapter method is one of the easiest methods to understand because we have a lot of real-life examples that show the analogy with it. The main purpose of this method is to create a bridge between two incompatible interfaces.
4 min read
Bridge Method - Python Design Patterns
The bridge method is a Structural Design Pattern that allows us to separate the Implementation Specific Abstractions and Implementation Independent Abstractions from each other and can be developed considering as single entities.The bridge Method is always considered as one of the best methods to organize the class hierarchy. Elements of Bridge Des
5 min read
Composite Method - Python Design Patterns
Composite Method is a Structural Design Pattern which describes a group of objects that is treated the same way as a single instance of the same type of the objects. The purpose of the Composite Method is to Compose objects into Tree type structures to represent the whole-partial hierarchies. One of the main advantages of using the Composite Method
5 min read
Decorator Method - Python Design Patterns
Decorator Method is a Structural Design Pattern which allows you to dynamically attach new behaviors to objects without changing their implementation by placing these objects inside the wrapper objects that contains the behaviors. It is much easier to implement Decorator Method in Python because of its built-in feature. It is not equivalent to the
3 min read
Article Tags :
Practice Tags :