20
votes

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.

11
I was looking something similar and found this: stackoverflow.com/questions/9884213/… - Gurpreet.S

11 Answers

20
votes

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 count

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

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
votes

Using itertools.count:

import itertools
for i in itertools.count():
    pass

In Python3, 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

Another way can be

def to_infinity():
    index=0
    while 1:
        yield index
        index += 1

for i in to_infinity():
    pass
5
votes

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)
3
votes

Here's another solution using the itertools module.

import itertools

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

Why not try itertools.count?

import itertools
for i in itertools.count():
    print i

which would just start printing numbers from 0 to ...

Try it out.

**I realize I'm a couple of years late but it might help someone else :)

1
votes

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

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!
0
votes

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.

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

-1
votes
my_list = range(10)

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