+ 1
How can I print infinity loop using for loop? [Phyton]
5 Answers
+ 3
1. You can loop infinitely through a finite iterable, using itertools.cycle
2. You can write a custom infinite generator (using a while loop) then iterate through it with for loop.
3. Just use a while loop :)
+ 3
MD. Ferdous Ibne Abu Bakar ,
if you don't need to get any value from the loop, we can use:
from itertools import repeat
for _ in repeat(None):
# ... your code to perform
if you need a value we can use itertools count() instead, which returns numbers
+ 3
A͢J ,
just to mention that using a 'dummy'-list and append items to simulate an infinite loop is acceptable for only a few iteration steps. but as soon as we iterate sequences with a great number of items, the 'dummy'-list will grow and the same is with the memory consumption.
+ 1
MD. Ferdous Ibne Abu Bakar
You can also take empty list and append item in that list:
l = [0]
for _ in l:
print (len(l))
l.append(_)
+ 1
Thank you all ❤️👍