Using and Implementing iterators with classes such as linked lists

Duncan Booth duncan at NOSPAMrcp.co.uk
Mon Dec 1 04:02:16 EST 2003


Adelein and Jeremy <adeleinandjeremy at yahoo.com> wrote in 
news:mailman.1210.1070252201.702.python-list at python.org:

> AFAIU, in my LinkedList class, I can either have the LinkedList be
> its
> own iterator by making its __iter__() method return self and defining
> a next() method, or I can have a separate iterator called from
> LinkedList's __iter__(). My view is that it would be best to have the
> LinkedList be its own iterator - is that the case? Or is an external
> iterator preferable in this case?
> 

It sounds a very bad idea to have LinkedList be its own iterator. If you 
did that then you could only have one iteration over each list at a time. 
In practical use, you will find that you want to iterate over a list, and 
you don't know or care whether another piece of code is already iterating 
over the same list.

The easiest way to handle it here is to use a generator to do the actual 
iteration:

def __iter__(self):
    def iterate(current):
        while current.next is not None:
            next = current.next
    	       yield current
            current = next
    return iterate(self)


-- 
Duncan Booth                                             duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?




More information about the Python-list mailing list