[Python-ideas] Rewriting the "roundrobin" recipe in the itertools documentation

Steven D'Aprano steve at pearwood.info
Thu Nov 16 18:06:30 EST 2017

On Thu, Nov 16, 2017 at 02:56:29PM -0500, Terry Reedy wrote:

> >3) using a while loop in code dealing with iterables,
> I agree that this is not necessary, and give a replacement below.

The OP isn't just saying that its unnecessary in this case, but that its 
unPythonic to ever use a while loop in code dealing with iterables. I 
disagree with that stronger statement.

> >def roundrobin(*iters):
> >     "roundrobin('ABC', 'D', 'EF') --> A D E B F C"
> >     # Perhaps "flat_zip_nofill" is a better name, or something similar
> >     sentinel = object()
> >     for tup in it.zip_longest(*iters, fillvalue=sentinel):
> >         yield from (x for x in tup if x is not sentinel)
> This adds and then deletes grouping and fill values that are not wanted. 
>  To me, this is an 'algorithm smell'.  One of the principles of 
> algorithm design is to avoid unnecessary calculations.  For an edge case 
> such as roundrobin(1000000*'a', ''), the above mostly does unnecessary work.

Its a recipe, not a tuned and optimized piece of production code.

And if you're going to criticise code on the basis of efficiency, then I 
would hope you've actually profiled the code first. Because it isn't 
clear to me at all that what you call "unnecessary work" is more 
expensive than re-writing the recipe using a more complex algorithm with 
calls to cycle and islice.

But I'm not here to nit-pick your recipe over the earlier ones.

> Since I have a competing 'improvement', I would hold off on a PR until 
> Raymond Hettinger, the itertools author, comments.

Raise a doc issue on the tracker, and take the discussion there. I think 
that this is too minor an issue to need long argument on the list. 
Besides, it's not really on-topic as such -- it isn't about a change to 
the language. Its about an implementation change to a recipe in the 


More information about the Python-ideas mailing list