44

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.

2
  • 2
    I was looking something similar and found this: stackoverflow.com/questions/9884213/… Commented Jan 12, 2018 at 23:41
  • @KarlKnechtel Imo, "infinite loop" and "looping from 1 to infinity" are not the same. while True is a good answer to the first, but not to the latter. Commented Sep 29, 2022 at 5:24

13 Answers 13

50

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

Comments

29

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

7 Comments

Hmm, but this is a while loop, not a for loop.
That is totally okay! I appreciate it though. Now I know while loops can be infinite as well! (:
@Britni.M I've updated the answer to include an appropriate generator in its simplest form.
1. I don't think you are correct that it will fail, see stackoverflow.com/questions/9860588/… 2. Even if it does "fail" by overflowing to a smaller value (as would happen in a language in C) it would still be infinite, just the numbers would not be unique
@Jon ah, interesting. Still, unnecessary code, but I've updated my answer to remove the incorrect assertion. Btw, I didn't down vote you (I noticed somebody came by and down voted both of us while I was typing this).
|
9

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)

Comments

5

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

1 Comment

This will create a big loop, yes, but not an infinite loop, so I don't think it answers the question. I mean, yes, it'll probably run past the death of our sun, but why bother when there are so many good solutions creating actually infinite loops?
4

Here's another solution using the itertools module:

import itertools

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

Comments

2

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

Comments

-1

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!

Comments

-1

Best way in my opinion:

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

The loop will run for thousands of years

1 Comment

How's that better than simple and obvious while True?
-2

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.

Comments

-2

we can actually have a for infinite loop

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

1 Comment

I do not think it's infinite. It will run out of memory or bounds eventually.
-3

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.

1 Comment

I do not think it's infinite. It will run out of memory or bounds eventually.
-3
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.

2 Comments

You can do without variable n: li.append(len(li))
I do not think it's infinite. It will run out of memory or bounds eventually.
-4

In Python 2.x, you can do:

my_list = range(10)

for i in my_list:
    print "hello python!!"
    my_list.append(i)

2 Comments

Would you like to improve your post? If yes, stackoverflow.com/editing-help but even more important is to add some explanation. Because code-only answers like this are rarely considered helpful.
This really does not answer the question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.