osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

itertools cycle() docs question


On 2019-08-21 11:27, Tobiah wrote:
> In the docs for itertools.cycle() there is
> a bit of equivalent code given:
> 
>      def cycle(iterable):
>          # cycle('ABCD') --> A B C D A B C D A B C D ...
>          saved = []
>          for element in iterable:
>              yield element
>              saved.append(element)
>          while saved:
>              for element in saved:
>                  yield element
> 
> 
> Is that really how it works?  Why make
> the copy of the elements?  This seems
> to be equivalent:
> 
> 
>      def cycle(iterable):
>          while iterable:
>              for thing in iterable:
>                  yield thing

Compare the results of

>>> import itertools as i
>>> def tobiahcycle(iterable):
...     while iterable:
...         for thing in iterable:
...             yield thing
... 
>>> def testiter():
...     yield input()
...     yield input()
... 

Now, see how many times input() gets called for itertools.islice()

>>> for v in i.islice(i.cycle(testiter()), 6): print(v)

Note that you only provide input twice, once for each yield statement.

Compare that to your tobiahcycle() method:

>>> for v in i.islice(tobiahcycle(testiter()), 6): print(v)

The yield gets called every time through the interator and it
doesn't produce the same results.

-tkc