Dr._Duck Dr._Duck - 1 month ago 8
Python Question

How to limit the no. of times cycle should run in python

from itertools import count,repeat,cycle
for i in cycle("raghav"):
print(i)
if len(i) >= 6:
break


My code is running infinitely even though i have limit the len, I have also tried
count(i) >= 6
but then it returns an error:


TypeError: a number is required

Answer
for i, x in enumerate(cycle('raghav')):
    print(x)
    if i >= 6:
        break

This is a perfect use case for enumerate

Oh, you want to repeatedly print 'raghav'. For that use repeat not cycle:

from itertools import repeat
for i, x in enumerate(repeat('raghav')):
    print(x)
    if i == 5:
        break

Or just

for i in range(5):
    print('raghav')