Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

itertools.repeat VS itertools.cycle

Is there any difference between itertools.repeat(n) and itertools.cycle(n)? As it seems, they produce the same output. Is one more efficient to use in a situation where I need an infinite loop of some element?

like image 526
maryAndreeva Avatar asked Nov 29 '22 23:11

maryAndreeva


2 Answers

Simply, itertools.repeat will repeat the given argument, and itertools.cycle will cycle over the given argument. Don't run this code, but for example:

from itertools import repeat, cycle

for i in repeat('abcd'): print(i)
# abcd, abcd, abcd, abcd, ...

for i in cycle('abcd'): print(i)
# a, b, c, d, a, b, c, d, ...
like image 154
Jared Goguen Avatar answered Dec 22 '22 21:12

Jared Goguen


These are equivalent but the first is clearer and a little faster:

it = repeat(x)
it = cycle([x])

However, cycle has the option of repeating entire sequences:

it = cycle(['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'])

And repeat has the option of setting a limit on the number of repetitions:

it = repeat(x, 5)         # Return five repetitions of x

Also, the intended use cases are different.

In particular, repeat was designed to provided a repeated argument to a mapped function:

it = imap(pow, repeat(2), range(10))

While cycle is intended for cyclic recurring behaviors. Here is a Python 3 example that returns 1/1 - 1/3 + 1/5 - 1/7 + 1/9 + ...:

it = accumulate(map(operator.truediv, cycle([1, -1]), count(1, 2)))

The latter example shows how all the parts fit together the create an "iterator algebra".

Hope you found this to be illuminating :-)

like image 24
Raymond Hettinger Avatar answered Dec 22 '22 20:12

Raymond Hettinger