I think there are two important things that need to be fixed.
First, your DoublyLinkedList class DoublyLinkedList not have a __iter__ method. You probably want to create one that returns an instance of ListIterator . You may be trying to do this manually, but this will be the usual approach.
Secondly, you need to fix the code in ListIterator to work properly. Currently, your __init__ method does not initialize things correctly, and your next method tries to access member variables, such as size , that do not exist.
An implementation will be implemented here, which I think will work:
def ListIterator(object): def __init__(self, node): self.current = node def __iter__(self): return self def next(self): if self.current is None: raise StopIteration() result = self.current.data self.current = self.current.next return result class DoublyLinkedList(object):
As a side note in your current code, you define classes without reason. This is good in Python 3 (where object will be the default base), but in Python 2 this will result in an "old style" class. Old classes are deprecated, and you will find that some language functions will not work with them properly (although not all functions related to iteration, as far as I know). On the other hand, if you are already using Python 3, you need to define the __next__ method in the iterator class, not next (without underscore).
source share