You could define alternate
like this:
import itertools
def alternate(*iters):
for elt in itertools.chain.from_iterable(
itertools.izip(*iters)):
yield elt
print list(alternate(xrange(1, 7, 2), xrange(2, 8, 2)))
This leaves open the question of what to do if one iterator stops before another.
If you'd like to continue until the longest iterator is exhausted, then you could use itertools.izip_longest
in place of itertools.izip
.
import itertools
def alternate(*iters):
for elt in itertools.chain.from_iterable(
itertools.izip_longest(*iters)):
yield elt
print list(alternate(xrange(1, 7, 2), xrange(2, 10, 2)))
This will put yield
[1, 2, 3, 4, 5, 6, None, 8]
Note None
is yielded when the iterator xrange(1,7,2) raises StopIteration (has no more elements).
If you'd like to just skip the iterator instead of yielding None
, you could do this:
Dummy=object()
def alternate(*iters):
for elt in itertools.chain.from_iterable(
itertools.izip_longest(*iters,fillvalue=Dummy)):
if elt is not Dummy:
yield elt