Here is an adapted version of the roundrobin recipe from the itertools documentation that should do what you want:
from itertools import cycle, islice def merge(a, b, pos): "merge('ABCDEF', [1,2,3], 3) --> AB 1 CD 2 EF 3" iterables = [iter(a)]*(pos-1) + [iter(b)] pending = len(iterables) nexts = cycle(iter(it).next for it in iterables) while pending: try: for next in nexts: yield next() except StopIteration: pending -= 1 nexts = cycle(islice(nexts, pending))
Example:
>>> list(merge(xrange(1, 9), 'abc', 3))
Or here is how roundrobin() can be used, since it is without any changes:
>>> x = [1,2,3,4,5,6,7,8] >>> y = ['a','b','c'] >>> list(roundrobin(*([iter(x)]*2 + [y]))) [1, 2, 'a', 3, 4, 'b', 5, 6, 'c', 7, 8]
Or an equivalent but slightly more readable version:
>>> xiter = iter(x) >>> list(roundrobin(xiter, xiter, y)) [1, 2, 'a', 3, 4, 'b', 5, 6, 'c', 7, 8]
Note that both of these methods work with any iterative, not just sequences.
Here is the original implementation of roundrobin() :
from itertools import cycle, islice def roundrobin(*iterables): "roundrobin('ABC', 'D', 'EF') --> ADEBFC" # Recipe credited to George Sakkis pending = len(iterables) nexts = cycle(iter(it).next for it in iterables) while pending: try: for next in nexts: yield next() except StopIteration: pending -= 1 nexts = cycle(islice(nexts, pending))