1

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?

3
  • I'm curious as to why you ask this question? Commented Apr 29, 2016 at 11:11
  • @joelgoldstick, i m making slides for high schools about python, i made one about while infinite loop and got curious - is there way to do infinite loop in python, so that's why asking Commented Apr 29, 2016 at 11:12
  • I 'm curious to why for i in range(0, 1, -1) : print("Hello") too doesn't work? Commented Jul 18, 2020 at 18:11

4 Answers 4

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
Sign up to request clarification or add additional context in comments.

Comments

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
...

Comments

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

7 Comments

What do you mean by cycle(_) (the underscore)?
it's a convention for throwaway variables
Yes, but it is not assigned in your example. Running that, you will get a NameError: name '_' is not defined.
By default, it is assigned to '' in my ipython console... You're right thx !
In interactive consoles it has a different meaning usually, there it represents the result of the last operation.
|
-7

Just pass could help with forever true value.

while True:
    pass

1 Comment

the question is "without using a while loop"

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.