Skip to content

Instantly share code, notes, and snippets.

@technige
Last active August 29, 2015 13:57
Show Gist options
  • Save technige/9358439 to your computer and use it in GitHub Desktop.
Save technige/9358439 to your computer and use it in GitHub Desktop.
Python 2 and 3 compatible round_robin function
from itertools import cycle, islice
def round_robin(*iterables):
""" Cycle through a number of iterables, returning
the next item from each in turn.
round_robin('ABC', 'D', 'EF') --> A D E B F C
Original recipe credited to George Sakkis
Python 2/3 cross-compatibility tweak by Nigel Small
"""
pending = len(iterables)
nexts = cycle(iter(it) for it in iterables)
while pending:
try:
for n in nexts:
yield next(n)
except StopIteration:
pending -= 1
nexts = cycle(islice(nexts, pending))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment