39

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.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Britni.M
  • 459
  • 1
  • 4
  • 6
  • 2
    I was looking something similar and found this: https://stackoverflow.com/questions/9884213/looping-from-1-to-infinity-in-python – Gurpreet.S Jan 12 '18 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. – Martin Prikryl Sep 29 '22 at 05:24

16 Answers16

44

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):
    ....
Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
25

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
orokusaki
  • 55,146
  • 59
  • 179
  • 257
  • 9
    Hmm, but this is a while loop, not a for loop. – Britni.M Dec 13 '15 at 17:27
  • 1
    That is totally okay! I appreciate it though. Now I know while loops can be infinite as well! (: – Britni.M Dec 13 '15 at 17:31
  • @Britni.M I've updated the answer to include an appropriate generator in its simplest form. – orokusaki Dec 13 '15 at 17:31
  • 1. I don't think you are correct that it will fail, see https://stackoverflow.com/questions/9860588/maximum-value-for-long-integer 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 Dec 13 '15 at 17:42
  • @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). – orokusaki Dec 13 '15 at 17:49
  • @orokusaki ...sounds suspicious, not everyone works for votes – omkaartg Jun 13 '18 at 19:49
  • @Omkaar.K glad to see new people signing up to this abandoned platform to read 3-year-old comments – orokusaki Jun 13 '18 at 20:10
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)
Jon
  • 1,122
  • 8
  • 10
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
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Sudarshan
  • 938
  • 14
  • 27
  • 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? – joanis Nov 13 '21 at 22:37
4

Here's another solution using the itertools module:

import itertools

for _ in itertools.repeat([]):  # return an infinite iterator
    pass
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
fizzybear
  • 1,197
  • 8
  • 22
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
...
finefoot
  • 9,914
  • 7
  • 59
  • 102
-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!
Dleep
  • 1,045
  • 5
  • 12
-1

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

  • 3
    Well, true, this creates an infinite for loop, but it is accompanied by infinite memory requirements, which is likely to be a problem for most code needing such an infinite loop. – joanis Mar 14 '22 at 12:42
-1

Best way in my opinion:

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

The loop will run for thousands of years

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

David Makogon
  • 69,407
  • 21
  • 141
  • 189
Akshat Tamrakar
  • 2,193
  • 2
  • 13
  • 21
-2

we can actually have a for infinite loop

list = []
for i in list:
   list.append(i)
   print("Your thing")
buddemat
  • 4,552
  • 14
  • 29
  • 49
-2

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.

DoctorHe
  • 65
  • 1
  • 9
  • This (imo bad) *solution* is already shown in several answers here, for example in the [answer by @DeepaRajesh](https://stackoverflow.com/q/34253996/850848#70631201). – Martin Prikryl Jan 27 '22 at 09:14
  • @MartinPrikryl if you test DeepaRajesh's answer, it actually doesn't work, len of the list must be at least 1. – DoctorHe Jan 27 '22 at 09:27
  • 1
    True. So see the answer by @SahajOberoi. And it's still not a good solution. Simple `while True` will do. – Martin Prikryl Jan 27 '22 at 09:37
-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.

Eric Aya
  • 69,473
  • 35
  • 181
  • 253
-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.

-4

In Python 2.x, you can do:

my_list = range(10)

for i in my_list:
    print "hello python!!"
    my_list.append(i)
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
sumit
  • 1
  • 5
    Would you like to improve your post? If yes, https://stackoverflow.com/editing-help but even more important is to add some explanation. Because code-only answers like this are rarely considered helpful. – Yunnosch Dec 13 '19 at 16:43
  • 1
    This really does not answer the question. – zvone Dec 13 '19 at 17:24
-4

i'm newbie in python but try this

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

can improve this code

  • 1
    This loop will run exactly two times so I'm not sure how it answers the question for getting an infinite loop... I'm guessing that you have the notion that doing `i=0` inside the loop will somehow *"reset"* the loop variable so it will run forever. This is not true. You should just run it and see for yourself... – Tomerikoo Nov 13 '21 at 13:29