I know that there is a nice recipe already that even made it into the Python documentation, but this one is more concise and at the same time simpler.
>>> list(roundrobin('ABC', 'D', 'EF')) ['A', 'D', 'E', 'B', 'F', 'C']
Python, 5 lines
1 2 3 4 5
from itertools import chain, izip_longest def roundrobin(*iterables): sentinel = object() return (x for x in chain(*izip_longest(fillvalue=sentinel, *iterables)) if x is not sentinel)
Tags: generator, itertools, python, roundrobin
Very nice :) Nice use of iterators there.