writable iterators?

Carl Banks pavlovevidence at gmail.com
Wed Jun 22 23:30:45 EDT 2011


On Wednesday, June 22, 2011 4:10:39 PM UTC-7, Neal Becker wrote:
> AFAIK, the above is the only python idiom that allows iteration over a sequence 
> such that you can write to the sequence.  And THAT is the problem.  In many 
> cases, indexing is much less efficient than iteration.

Well, if your program is such that you can notice a difference between indexing and iteration, you probably have better things to worry about.  But whatever.  You can get the effect you're asking for like this:


class IteratorByProxy(object):
    def __init__(self,iterable):
        self.set(iterable)
    def __iter__(self):
        return self
    def next(self):
        return self.current_iter.next()
    def set(self,iterable):
        self.current_iter = iter(iterable)

s = IteratorByProxy(xrange(10))
for i in s:
    print i
    if i == 6:
        s.set(xrange(15,20))


Carl Banks



More information about the Python-list mailing list