I've written this kind of iterator before, using collections.deque, which personally I find a little more elegant than the list based approach:
from collections import deque def interleave(*iterables): iters = deque(iter(iterable) for iterable in iterables) while iters: it = iters.popleft() try: yield it.next() except StopIteration: continue iters.append(it) >>> for item in interleave(xrange(6), "abc", ["gamma", "delta"]): print item 0 a gamma 1 b delta 2 c 3 4 5 I too came across the need for it while dealing with infinite generators, where itertools.chain obviously won't suffice. If you extended this approach to the class based solution it would have the advantage of making append() an 0(1) operation, which is nice. [EMAIL PROTECTED] wrote: > >> Sorry, my description was not very good, I meant something behaving as: > >> > >> >>>example=Liter("abc","12345","XY") > >> >>>for x in example: print x, > >> > >> a 1 X b 2 Y c 3 4 5 > >> > >> or for that append() method, > >> > >> >>>example=Liter("abc", "12345") > >> >>>for i in range(3): print example.next(), > >> > >> a 1 b > >> > >> >>>example.append("XY") > >> >>>for x in example: print x, > >> > >> 2 c X 3 Y 4 5 > > >Check the module I posted on > >http://rafb.net/paste/results/CRT7bS68.html. append() makes things more > >complicated -- mainly because generators don't accept attributes, so it > >has to be wrapped in a class -- but the simple generator (without > >append) is more manageable > > Thank you very much for your solution. Actually I needed that append() > method quite a lot, so maybe my solution (posted at the beginning of this > thread) was not that stupid :) (to inflate my ego a bit) > > Anyway, this is roughly what I used it for; is it a sane use of iterators? > > I was looking for the Holy Grail. I had an iterator 'quest' that produced > either junk that was to be thrown away, or the Holy Grail itself, or > another iterator of the same kind (that had to be searched for the Holy > Grail as well). The iterators were potentially infinite. The code was > rougly: > > quest=Liter(quest) > for x in quest: > if is_Holy_Grail(x): > share_and_enjoy(x) > break > elif is_another_iterator(x): > quest.append(x) > > > Best regards > P. -- http://mail.python.org/mailman/listinfo/python-list