How to write this iterator?

Daniel Dittmar daniel.dittmar at sap.corp
Mon Sep 19 07:50:45 EDT 2005


severa at sophia.dtp.fmph.uniba.sk wrote:
> 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?

A generator version:

def iterconcat (collectionlist):
     for collection in collectionlist:
         for element in collection:
             yield element

Extending collectionlist at runtime will work only with lists and 
similar collections. And you'll need to keep a reference to it as well. 
And it would be called after all the others, which matches your 
description, but not your code.

Daniel



More information about the Python-list mailing list