Are infinite for loops possible in Python? [duplicate]
Asked Answered
H

15

41

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.

Habit answered 13/12, 2015 at 17:23 Comment(2)
I was looking something similar and found this: #9884713Pus
@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.Nievelt
R
49

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):
    ....
Radiogram answered 13/12, 2015 at 17:43 Comment(0)
A
28

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
Adjacent answered 13/12, 2015 at 17:26 Comment(7)
Hmm, but this is a while loop, not a for loop.Habit
That is totally okay! I appreciate it though. Now I know while loops can be infinite as well! (:Habit
@Habit I've updated the answer to include an appropriate generator in its simplest form.Adjacent
1. I don't think you are correct that it will fail, see #9861088 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 uniqueKaph
@Kaph 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).Adjacent
@Adjacent ...sounds suspicious, not everyone works for votesFirry
@Omkaar.K glad to see new people signing up to this abandoned platform to read 3-year-old commentsAdjacent
K
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)
Kaph answered 13/12, 2015 at 17:24 Comment(0)
F
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
Fasto answered 22/6, 2018 at 7:16 Comment(1)
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?Tati
W
4

Here's another solution using the itertools module:

import itertools

for _ in itertools.repeat([]):  # return an infinite iterator
    pass
Waler answered 13/12, 2019 at 16:58 Comment(0)
C
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
...
Custombuilt answered 26/4, 2021 at 10:33 Comment(0)
Q
-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!
Quasar answered 14/12, 2015 at 5:57 Comment(0)
K
-1

Best way in my opinion:

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

The loop will run for thousands of years

Kook answered 29/5, 2022 at 9:37 Comment(1)
How's that better than simple and obvious while True?Nievelt
O
-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.

Overwind answered 14/9, 2021 at 11:57 Comment(0)
C
-2

we can actually have a for infinite loop

list = []
for i in list:
   list.append(i)
   print("Your thing")
Congo answered 8/1, 2022 at 9:48 Comment(1)
I do not think it's infinite. It will run out of memory or bounds eventually.Nievelt
G
-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.

Gaeta answered 27/1, 2022 at 9:7 Comment(3)
This (imo bad) solution is already shown in several answers here, for example in the answer by @DeepaRajesh.Nievelt
@MartinPrikryl if you test DeepaRajesh's answer, it actually doesn't work, len of the list must be at least 1.Gaeta
True. So see the answer by @SahajOberoi. And it's still not a good solution. Simple while True will do.Nievelt
L
-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.

Loom answered 4/9, 2018 at 11:32 Comment(1)
I do not think it's infinite. It will run out of memory or bounds eventually.Nievelt
P
-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.

Prose answered 25/6, 2020 at 9:34 Comment(2)
You can do without variable n: li.append(len(li))Pintle
I do not think it's infinite. It will run out of memory or bounds eventually.Nievelt
B
-4

In Python 2.x, you can do:

my_list = range(10)

for i in my_list:
    print "hello python!!"
    my_list.append(i)
Boeschen answered 13/12, 2019 at 16:38 Comment(2)
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.Orphanage
This really does not answer the question.Kerikeriann
L
-4

i'm newbie in python but try this

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

can improve this code

Lohrman answered 13/11, 2021 at 7:0 Comment(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...Longo

© 2022 - 2025 — McMap. All rights reserved.