I want a generator that cycle infinitely through a list of values.
Here is my solution, but I may be missing a more obvious one.
The ingredients: a generator function that flatten an infinitely nested list, and a list appendant to itself
for it in x:
if isinstance(it, list):
yield from ge(it)
x = l[:]
yield from ge(x)
g = infinitecyclegenerator([1,2,3])
You can use
itertools.cycle to achieve the same result
Make an iterator returning elements from the iterable and saving a copy of each. When the iterable is exhausted, return elements from the saved copy.
Emphasis mine. Your only concern about memory would be saving a copy of each item returned by the iterator.
>>> from itertools import cycle >>> c = cycle([1,2,3]) >>> next(c) 1 >>> next(c) 2 >>> next(c) 3 >>> next(c) 1 >>> next(c) 2 >>> next(c) 3