Infinite for loops possible in Python?
To answer your question using a for loop as requested, this would loop forever as 1 will never be equal to 0:
for _ in iter(int, 1): pass
If you wanted an infinite loop using numbers that were incrementing as per the first answer you could use itertools.count
:
from itertools import countfor i in count(0): ....
The quintessential example of an infinite loop in Python is:
while True: pass
To apply this to a for loop, use a generator (simplest form):
def infinity(): while True: yield
This can be used as follows:
for _ in infinity(): pass
Yes, use a generator that always yields another number:Here is an example
def zero_to_infinity(): i = 0 while True: yield i i += 1for x in zero_to_infinity(): print(x)
It is also possible to achieve this by mutating the list you're iterating on, for example:
l = [1]for x in l: l.append(x + 1) print(x)