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?
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, ...
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 :-)
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