3

Is there way to write an infinite for loop in Python?

for t in range(0,10):
    if(t == 9): t= 0 # will this set t to 0 and launch infinite loop? No!
    print(t)

Generally speaking, is there way to write infinite pythonic for loop like in java without using a while loop?

Gilbert Allen
  • 335
  • 2
  • 12
ERJAN
  • 22,540
  • 20
  • 65
  • 127

4 Answers4

8

The itertools.repeat function will return an object endlessly, so you could loop over that:

import itertools
for x in itertools.repeat(1):
    pass
snakecharmerb
  • 36,887
  • 10
  • 71
  • 115
7

To iterate over an iterable over and over again, you would use itertools.cycle:

from itertools import cycle
for t in cycle(range(0, 4)):
    print(t)

This will print the following output:

0
1
2
3
0
1
2
3
0
1
...
Byte Commander
  • 5,981
  • 4
  • 37
  • 66
4

You should create your own infinite generator with cycle

from itertools import cycle

gen = cycle([0])

for elt in gen:
    # do stuff

or basically use itertools.count():

for elt in itertools.count():
    # do stuff
mvelay
  • 1,500
  • 1
  • 10
  • 23
-7

Just pass could help with forever true value.

while True:
    pass
Vishal Yarabandi
  • 387
  • 1
  • 3
  • 9