abstract data types using iterators with the definition of the bagiterator class and the modifications to the bag classwe can now use python' for loop with bag instance when the for loop for item in bag printitem is executedpython automatically calls the iter method on the bag object to create an iterator object figure illustrates the state of the bagiterator object immediately after being created notice the bagitems field of the iterator object references theitems field of the bag object this reference was assigned by the constructor when the bagiterator object was created bagvectorcuritem curitem _bagiterator theitems bag figure the bag and bagiterator objects before the first loop iteration the for loop then automatically calls the next method on the iterator object to access the next item in the container the state of the iterator object changes with the curitem field having been incremented by one this process continues until stopiteration exception is raised by the next method when the items have been exhausted as indicated by the curitem after all of the items have been processedthe iteration is terminated and execution continues with the next statement following the loop the following code segment illustrates how python actually performs the iteration when for loop is used with an instance of the bag classcreate bagiterator object for mybag iterator mybag __iter__(repeat the while loop until break is called while true tryget the next item from the bag if there are no more itemsthe stopiteration exception is raised item iterator __next__(perform the body of the for loop printitem catch the exception and break from the loop when we are done except stopiterationbreak