designing an iterator to use python' traversal mechanism with our own abstract data typeswe must define an iterator classwhich is class in python containing two special methodsiter and next iterator classes are commonly defined in the same module as the corresponding container class the implementation of the bagiterator class is shown in listing the constructor defines two data fields one is an alias to the list used to store the items in the bagand the other is loop index variable that will be used to iterate over that list the loop variable is initialized to zero in order to start from the beginning of the list the iter method simply returns reference to the object itself and is always implemented to do so listing the bagiterator classwhich is part of the linearbag py module an iterator for the bag adt implemented as python list class _bagiterator def __init__selfthelist )self _bagitems thelist self _curitem def __iter__self )return self def __next__self )if self _curitem lenself _bagitems item self _bagitemsself _curitem self _curitem + return item else raise stopiteration the next method is called to return the next item in the container the method first saves reference to the current item indicated by the loop variable the loop variable is then incremented by one to prepare it for the next invocation of the next method if there are no additional itemsthe method must raise stopiteration exception that flags the for loop to terminate finallywe must add an iter method to our bag classas shown heredef __iter__self )return _bagiteratorself _theitems this methodwhich is responsible for creating and returning an instance of the bagiterator classis automatically called at the beginning of the for loop to create an iterator object for use with the loop construct