There is a function that does this exactly in python docs that works with n arrays
from itertools import * 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))
I came up with another one that will continue to repeat through shorter arrays if they end earlier:
from itertools import * def repeatrobin(*iterables): cycles = cycle(map(cycle, iterables)) stop = iter(xrange(max(map(len, iterables)) * len(iterables) - 1)) for c in cycles: yield c.next() stop.next() >>> list(repeatrobin(('A', 'B', 'C', 'D', 'E', 'F', 'G'), (1, 2, 3, 4))) ['A', 1, 'B', 2, 'C', 3, 'D', 4, 'E', 1, 'F', 2, 'G', 3] >>> list(repeatrobin(('A', 'B', 'C', 'D', 'E'), (1, 2, 3), ('*',))) ['A', 1, '*', 'B', 2, '*', 'C', 3, '*', 'D', 1, '*', 'E', 2, '*']