How to write this iterator?

severa at severa at
Mon Sep 19 11:05:04 CEST 2005

Given a list of iterators, I'd like to have a new one that would 
cyclically walk over the list calling the next() method of the iterators 
(removing any iterator which is exhausted). It should also support adding 
a new iterator to the list; it should be added in front of the current 
position (so that it's called only after all the others). This is what I 
was able to write with my zero python skills (self.iters is the list of 
iterators, self.i is the index of the iterator that should be used next). 
Is there a nicer/more pythonic solution, maybe using generators?

class Liter(object):

    def __init__(self, *iters):
        self.iters=[iter(x) for x in iters]

    def append(self,what):

    def __iter__(self):
        return self

    def next(self):
        while True:
            except StopIteration:
                del self.iters[self.i]
            except IndexError:
                if len(self.iters) is 0:
                    raise StopIteration
                return result

More information about the Python-list mailing list