I'd like to cycle through a list repeatedly (N times) via an iterator, so as not to actually store N copies of the list in memory. Is there a built-in or elegant way to do this without writing my own generator?
Ideally, itertools.cycle(my_list) would have a second argument to limit how many times it cycles... alas, no such luck.
The cycle() function accepts an iterable and generates an iterator, which contains all of the iterable's elements. In addition to these elements, it contains a copy of each element.
In repeat() we give the data and give the number, how many times the data will be repeated. If we will not specify the number, it will repeat infinite times. In repeat(), the memory space is not created for every variable.
It is a function that takes a series of iterables and returns one iterable. It groups all the iterables together and produces a single iterable as output.
All the other answers are excellent. Another solution would be to use islice
. This allows you to interrupt the cycle at any point:
>>> from itertools import islice, cycle
>>> l = [1, 2, 3]
>>> list(islice(cycle(l), len(l) * 3))
[1, 2, 3, 1, 2, 3, 1, 2, 3]
>>> list(islice(cycle(l), 7))
[1, 2, 3, 1, 2, 3, 1]
import itertools
itertools.chain.from_iterable(itertools.repeat([1, 2, 3], 5))
Itertools is a wonderful library. :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With