osdir.com


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

itertools cycle() docs question


On 8/21/2019 2:27 PM, 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

Try this experiment:

from itertools import cycle

def cycle2(iterable):
     while iterable:
         for thing in iterable:
             yield thing

for i, v in zip(range(20), cycle(i*i for i in range(4))):
     print(i, v)

for i, v in zip(range(20), cycle2(i*i for i in range(4))):
     print(i, v)

-- 
Terry Jan Reedy