Iterator for Custom Sequence
Jonathan Hogg
jonathan at onegoodidea.com
Tue Jul 16 07:27:45 EDT 2002
On 16/7/2002 12:15, in article 87u1mzq5xw.fsf at athens.localdomain, "Patrick
W" <csposting at yahoo.com.au> wrote:
> class LinkedList:
> ....
> def __iter__(self):
> def genitems(ls):
> n = ls.head
> while n.data is not None:
> yield n.data
> n = n.next
> return genitems(self)
> ....
>
> This does the job, but is it eccentric or counter-Pythonic? If so,
> what's the conventional way to provide an iterator for a custom
> sequence?
I'm not sure why you've used a nested function. I would have written this
simply as:
class LinkedList:
....
def __iter__(self):
node = self.head
while node.next is not None:
yield node.data
node = node.next
....
When you call 'iter' on an object it should return an iterator. A generator
returns an iterator when called. So making '__iter__' a generator suffices.
In fact this is the main place I use generators.
I made a couple of changes other than removing the function: I like 'node'
better than 'n', and I think testing if 'node.data' is None is bogus as you
might want to store None in the list. It makes more sense (and is more
normal in linked-lists) to check if 'node.next' is None, since the last item
should have no next item (obviously your other methods would need to match
this convention).
Jonathan
More information about the Python-list
mailing list