[Python-ideas] itertools.documentation.ncycles is a bit of a sore thumb

Jacob Holm jh at improva.dk
Wed Aug 3 20:41:09 CEST 2011


On 2011-08-03 17:54, Raymond Hettinger wrote:
> 
> On Aug 3, 2011, at 9:39 AM, Julian Berman wrote:
> 
>> def ncycles(iterable, n):
>>  return chain.from_iterable(repeat(tuple(iterable), n))
>>
>> Somewhere along the line something was going to need to buffer that, but it'd be nicer if the example didn't have the buffering done all at once at the outset as it is now.
>>
>> Perhaps more importantly, though, is there a specific objection to just adding a count to itertools.cycle much like itertools.repeat has now for this?
> 
> 
> The optional argument has never been requested and I don't see ncycles() being used enough in-practice to warrant adding complexity to the API.  The recipe for ncycles() is included in the docs as a way of teaching how itertools can be composed.   
> 

How about using this alternate recipe then:

  def ncycles(iterable, n):
      return chain.from_iterable(tee(iterable, n))

Or even:

  from copy import copy
  def ncycles(iterable, n):
      it, = tee(iterable, 1)
      return chain.from_iterable(
        copy(it) if i<n else it for i in xrange(1,n+1)
        )


- Jacob



More information about the Python-ideas mailing list