First page Back Continue Last page Overview Graphics

Exercise

Write a generator, that is equivalent to itertools.cycle.

def cycle(iterable):

saved = []

for element in iterable:

yield element

saved.append(element)

while saved:

for element in saved:

yield element

numbers = cycle("abcde")

for _ in range(12):

print(next(numbers), end=", ")

“iterable is exhausted

after the for loop, that's

why we have to save

the value in the “saved”

list