iterators iteration is an important concept in the design of data structures we introduced python' mechanism for iteration in section in shortan iterator for collection provides one key behaviorit supports special method named next that returns the next element of the collectionif anyor raises stopiteration exception to indicate that there are no further elements fortunatelyit is rare to have to directly implement an iterator class our preferred approach is the use of the generator syntax (also described in section )which automatically produces an iterator of yielded values python also helps by providing an automatic iterator implementation for any class that defines both len and getitem to provide an instructive example of low-level iteratorcode fragment demonstrates just such an iterator class that works on any collection that supports both len and getitem this class can be instantiated as sequenceiterator(datait operates by keeping an internal reference to the data sequenceas well as current index into the sequence each time next is calledthe index is incrementeduntil reaching the end of the sequence class sequenceiterator """an iterator for any of python sequence types "" def init (selfsequence) """create an iterator for the given sequence ""keep reference to the underlying data self seq sequence will increment to on first call to next self - def next (self) """return the next elementor else raise stopiteration error ""advance to next index self + if self len(self seq)return the data element return(self seq[self ] else raise stopiterationthere are no more elements def iter (self) """by conventionan iterator must return itself as an iterator "" return self code fragment an iterator class for any sequence type