Using and Implementing iterators with classes such as linked lists

Adelein and Jeremy adeleinandjeremy at
Mon Dec 1 19:46:33 CET 2003

First of all, I apologize for the double posting - I thought there
was some problem with the Yahoo group so I joined the main mailing
list and repeated instead of waiting as I should have.

Thanks for the speedy and helpful responses. I now grok the downside
of using internal iterators. Now, for the external iterator, I am
thinking that I would do this:

class LinkedList:


    def __iter__(self):
        return LinkedListIterator(self.__head)

class LinkedListIterator:

    def __init__(self, headNode):
        self.__current = headNode

    def __iter__(self):
        return self

    def next(self):
        if == None:
            raise StopIteration
        self.__current =

Of course, this LinkedListIterator is for a LinkedList that has a
dummy header node, but the concept is the same in any case. I
understand the concept of generators, but I do not fully comprehend
all of the nuances; for that and a few other reasons, I am avoiding
their use here. A few questions though:

1) I think it is best to pass only one node to the iterator, as
opposed to the whole list - is that "correct"?

2) The __iter__() method is necessary in LinkedListIterator, am I

3) Does this code display suitable Python idiomatic expression? For
example, and in particular, is my use of '==' (as opposed to 'is
not') acceptable and good from this viewpoint?

Thanks again,

- Jeremy

Do you Yahoo!?
Free Pop-Up Blocker - Get it now

More information about the Python-list mailing list