what should __iter__ return?

Gregory Ewing greg.ewing at canterbury.ac.nz
Tue Sep 7 21:40:48 EDT 2010


Thomas Jollans wrote:

> Hmm. Modifying an object while iterating over it isn't a great idea, ever:

I wouldn't say never. Algorithms that calculate some kind of
transitive closure can be expressed rather neatly by appending
items to a list being iterated over.

You can accommodate that kind of thing by writing the iterator
like this:

   def __iter__(self):
     i = 0
     while i < len(self):
       yield self[i]
       i += 1

-- 
Greg



More information about the Python-list mailing list