'Are infinite for loops possible in Python?

Is it possible to get an infinite loop in for loop?

My guess is that there can be an infinite for loop in Python. I'd like to know this for future references.



Solution 1:[1]

You can use the second argument of iter(), to call a function repeatedly until its return value matches that argument. This would loop forever as 1 will never be equal to 0 (which is the return value of int()):

for _ in iter(int, 1):
    pass

If you wanted an infinite loop using numbers that are incrementing you could use itertools.count:

from itertools import count

for i in count(0):
    ....

Solution 2:[2]

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

Solution 3:[3]

Yes, use a generator that always yields another number: Here is an example

def zero_to_infinity():
    i = 0
    while True:
        yield i
        i += 1

for 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)

Solution 4:[4]

In Python 3, range() can go much higher, though not to infinity:

import sys

for i in range(sys.maxsize**10):  # you could go even higher if you really want but not infinity
    pass

Solution 5:[5]

Here's another solution using the itertools module:

import itertools

for _ in itertools.repeat([]):  # return an infinite iterator
    pass

Solution 6:[6]

It's also possible to combine built-in functions iter (see also this answer) and enumerate for an infinite for loop which has a counter:

for i, _ in enumerate(iter(bool, True)):
    input(i)

Which prints:

0
1
2
3
4
...

This uses iter to create an infinite iterator and enumerate provides the counting loop variable. You can even set a start value other than 0 with enumerate's start argument:

for i, _ in enumerate(iter(bool, True), start=42):
    input(i)

Which prints:

42
43
44
45
46
...

Solution 7:[7]

Best way in my opinion:

for i in range(int(1e18)):
    ...

The loop will run for thousands of years

Solution 8:[8]

While there have been many answers with nice examples of how an infinite for loop can be done, none have answered why (it wasn't asked, though, but still...)

A for loop in Python is syntactic sugar for handling the iterator object of an iterable an its methods. For example, this is your typical for loop:

for element in iterable:
    foo(element)

And this is what's sorta happening behind the scenes:

iterator = iterable.__iter__()
try:
    while True:
        element = iterator.next()
        foo(element)
except StopIteration:
    pass

An iterator object has to have, as it can be seen, anextmethod that returns an element and advances once (if it can, or else it raises a StopIteration exception).

So every iterable object of which iterator'snextmethod does never raise said exception has an infinite for loop. For example:

class InfLoopIter(object):
    def __iter__(self):
        return self # an iterator object must always have this
    def next(self):
        return None

class InfLoop(object):
    def __iter__(self):
        return InfLoopIter()

for i in InfLoop():
    print "Hello World!" # infinite loop yay!

Solution 9:[9]

we can actually have a for infinite loop

list = []
for i in list:
   list.append(i)
   print("Your thing")

Solution 10:[10]

i found a way without using yield or a while loop. my python version is python 3.10.1

x = [1]
for _ in x:
    x.append(1)
    print('Hello World!')

if you need loop count, you can use i+1:

x = [1]
for i in x:
    x.append(i+1)
    print(f'Hello {i}')

you should know that this is not really an "infinite" loop.
because as the loop runs, the list grows and eventually, you will run out of ram.

Solution 11:[11]

Python infinite for loop

Well, there are a few ways, but the easiest one I found is to Iterate over a list

To understand this you must be knowing about:

  • python basics
  • python loops
  • python lists ( and also its append() function

The syntax is something like this...

l = ['#']   # Creating a list

for i in l:   # Iterating over the same list
    print(l)
    l.append(i)   # Appending the same element

With every iteration, the an element gets appended to the list. This way the loop never stops iterating.

Happy coding : )

Solution 12:[12]

You can configure it to use a list. And append an element to the list everytime you iterate, so that it never ends.

Example:

list=[0]
t=1
for i in list:
        list.append(i)
        #do your thing.
        #Example code.
        if t<=0:
                break
        print(t)
        t=t/10

This exact loop given above, won't get to infinity. But you can edit the if statement to get infinite for loop.

I know this may create some memory issues, but this is the best that I could come up with.

Solution 13:[13]

n = 0
li = [0]
for i in li:
    n += 1
    li.append(n)
    print(li)

In the above code, we iterate over the list (li).

  • So in the 1st iteration, i = 0 and the code in for block will run, that is li will have a new item (n+1) at index 1 in this iteration so our list becomes [ 0, 1 ]
  • Now in 2nd iteration, i = 1 and new item is appended to the li (n+1), so the li becomes [0, 1, 2]
  • In 3rd iteration, i = 2, n+1 will be appended again to the li, so the li becomes [ 0, 1, 2, 3 ]

This will keep on going as in each iteration the size of list is increasing.

Solution 14:[14]

The other solutions solutions have a few issues, such as:

  • consuming a lot of memory which may cause memory overflow
  • consuming a lot of processor power.
  • creating deadlock.
  • using 3rd party library

Here is an answer, which will overcome these problems.

from asyncio import run, sleep


async def generator():
    while True:
        await sleep(2)
        yield True


async def fun():
    async for _ in generator():
        print("Again")


if __name__ == '__main__':
    run(fun())

In case you want to do something that will take time, replace sleep with your desired function.

Solution 15:[15]

i'm newbie in python but try this

 for i in range(2):
         # your code here
         i = 0

can improve this code