maryAndreeva maryAndreeva - 1 year ago 64
Python Question

itertools.repeat VS itertools.cycle

Is there any difference between

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