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
  • 343
  • 2
  • 13
ERJAN
  • 23,696
  • 23
  • 72
  • 146

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
  • 47,570
  • 11
  • 100
  • 153
6

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
  • 6,506
  • 6
  • 44
  • 71
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,520
  • 1
  • 10
  • 23
-7

Just pass could help with forever true value.

while True:
    pass
Vishal Yarabandi
  • 427
  • 1
  • 4
  • 9