Using and Implementing iterators with classes such as linkedlists

Terry Reedy tjreedy at udel.edu
Mon Dec 1 16:25:56 EST 2003


"Adelein and Jeremy" <adeleinandjeremy at yahoo.com> wrote in message
news:mailman.13.1070304403.16879.python-list at python.org...
> 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 self.__current.next == None:
>             raise StopIteration
>         self.__current = self.__current.next
>         return self.__current.next
>
> 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.

My initial answer would have been the same as Duncan's -- __iter__
returning a generator-iterator.  I *strongly* recommend that read more
about them until you feel comfortable using one.  This is one of their
designed uses.  Less typing and more speed than an instance of a
separate iterator class.  The latter is more general but the extra
generality is useless 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"?

Give the iterator-maker (class or genfunc) whatever it needs to start
iteration.  'Best' is what it easiest.

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

All iterators should have __iter__ returning self so user can accept
either iterable, self iterating or not, or iterater and call
iter(itwhatever) and get iterator without trying to test.

> 3) Does this code display suitable Python idiomatic expression?

Ignoring preferability of gen-it, overall, yes.

>For
> example, and in particular, is my use of '==' (as opposed to 'is
> not') acceptable and good from this viewpoint?

No.  Generic comparison 'x==None' is slower than 'x is None',
althought not as bad as 'x==True' instead of 'x' after 'if'.  The
singleton-ness of None is a feature of Python intended to be used as
in latter expression.

Terry J. Reedy






More information about the Python-list mailing list