Welcome, guest | Sign In | My Account | Store | Cart

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)

1 comment

James Mills 8 years ago  # | flag

Very nice :) Nice use of iterators there.

Created by Jan Müller on Wed, 13 Nov 2013 (MIT)
Python recipes (4591)
Jan Müller's recipes (2)

Required Modules

  • (none specified)

Other Information and Tasks