Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an elegant way to cycle through a list N times via iteration (like itertools.cycle but limit the cycles)?

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.

like image 837
JJC Avatar asked Apr 26 '12 00:04

JJC


People also ask

What does the cycle function from Itertools module do?

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.

What should you keep in mind when using the repeat () function of the Itertools module?

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.

What is Itertools chain in Python?

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.


2 Answers

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]
like image 194
senderle Avatar answered Oct 04 '22 12:10

senderle


import itertools
itertools.chain.from_iterable(itertools.repeat([1, 2, 3], 5))

Itertools is a wonderful library. :)

like image 37
Casey Kuball Avatar answered Oct 04 '22 10:10

Casey Kuball