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.
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.
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:
And this is what's sorta happening behind the scenes:
An iterator object has to have, as it can be seen, a
next
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's
next
method does never raise said exception has an infinite for loop. For example:To answer your question using a for loop as requested, this would loop forever as 1 will never be equal to 0:
If you wanted an infinite loop using numbers that were incrementing as per the first answer you could use
itertools.count
:Yes, use a generator that always yields another number: Here is an example
It is also possible to achieve this by mutating the list you're iterating on, for example:
You can configure it to use a list. And append an element to the list everytime you iterate, so that it never ends.
Example:
This exact loop given above, won't get to infinity. But you can edit the
if
statement to get infinitefor
loop.I know this may create some memory issues, but this is the best that I could come up with.
Using itertools.count:
In Python3, range() can go much higher, though not to infinity:
Another way can be
The quintessential example of an infinite loop in Python is:
To apply this to a for loop, use a generator (simplest form):
This can be used as follows: