Search code examples
pythonpython-3.xpython-itertoolscycle

How to break cycle after a specific number of iterations in itertools?


I have a cycle that repeats, and I want it to stop repeating after let's say 5 repeats:

from itertools import cycle
a = [1,2,3]

for i in cycle(a):
    print (i)
    if i == 5:
       break

what I expect is 123,123,123,123,123. it cycling 5 times before breaking. Instead it keeps going forever. How do I go about making it cycle only 5 times before moving on to the next code?


Solution

  • itertools provides all the tools here; just wrap in islice to limit the number of outputs (in this case to five times the number of inputs):

    from itertools import cycle, islice
    a = [1,2,3]
    
    for i in islice(cycle(a), 5*len(a)):  # Loops 15 times with a single value each time
        print(i)
    
    # Or equivalently:
    from itertools import chain, repeat
    
    for i in chain.from_iterable(repeat(a, 5)):
        print(i)
    

    If you just want the whole contents of a repeated three times (getting [1, 2, 3] on each loop instead of 1, then 2, then 3), you'd use repeat instead:

    from itertools import repeat
    a = [1,2,3]
    
    for x in repeat(a, 5):  # Loops five times, producing the same list over and over
        print(x)