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 refe
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
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
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).
This will keep on going as in each iteration the size of list is increasing.
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 :)
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, anext
method that returns an element and advances once (if it can, or else it raises a StopIteration exception).
So every iterable object of which iterator'snext
method 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!
my_list = range(10)
for i in my_list:
print ("hello python!!")
my_list.append(i)