Using itertools.count:
import itertools
for i in itertools.count(start=1):
if there_is_a_reason_to_break(i):
break
In Python 2, range() and xrange() were limited to sys.maxsize. 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
if there_is_a_reason_to_break(i):
break
So it's probably best to use count().
Using itertools.count:
import itertools
for i in itertools.count(start=1):
if there_is_a_reason_to_break(i):
break
In Python 2, range() and xrange() were limited to sys.maxsize. 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
if there_is_a_reason_to_break(i):
break
So it's probably best to use count().
def to_infinity():
index = 0
while True:
yield index
index += 1
for i in to_infinity():
if i > 10:
break
[Thought experiment] Achieving one-line infinite loops in Python
Infinite loops using 'for' in Python - Stack Overflow
Allow `range(start, None, step)` for an endless range - Ideas - Discussions on Python.org
How do I make an infinite for loop in Python (without using a while loop)? - Stack Overflow
Videos
DISCLAIMER: This post is mainly just curious thoughts, it has nothing to do with real-life application or good practice. So please don't actually use any examples provided.
Python is (or at least was) rather famous for its possibilities for one-liners (programs occupying only a single line of code) some time ago. A lot of things can be achieved like this, but among the most puzzling things must be infinite loops; they aren't exactly easy to implement with the tools we have available.
An infinite loop usually requires the use of a while-loop, because for-loops have a beginning and an end. Using a while-loop in one-liners is problematic, though, because you may only use it once, on the top level. This is due to how Python restricts block structures to either be separated by whitespace (and proper indentation), or to only have a single depth level following it. In other words,
while True: print("This works!")is valid Python, but
while True: if 1 == 1: print("But this doesn't...)is not.
We do have another "kind" of loop, though; list comprehensions. They are unique in that they may be nested as we see fit, all while using only a single line.
[["Order pizza." for _ in range(6)] for _ in range(42)]
But this doesn't give us an infinite loop; even if we simply input a ridiculously large number to range, it's still technically finite no matter what kind of hardware we're using. Thus, a different approach is required. I mentioned how infinite loops usually require the use of while-loops in Python. We can, however, utilise a certain property of Python to create an infinite loop with for-loops.
nums = [1, 2, 3, 4]
for num in nums:
print(num)Okay, that prints out four numbers. Not exactly infinite. But if we tweak our approach a little...
nums = [1]
for num in nums:
print(num)
nums.append(num + 1)We actually get... as many numbers as the computer's memory allows. With this, we can essentially get something like this to work:
nums=[1];[(print(num) and nums.append(num+1)) for num in nums]
(Disclaimer; I never tested if that actually runs.)
It's not a pure one-liner, because it still technically requires two lines (fused together with a semicolon), but it's a proof-of-concept. I initially tried to make it work without having to define a variable, but failed to find a way.
I hope this was mildly interesting, I don't usually write stuff like this. Just found it curious myself, so why not share the thought? Maybe someone can even improve on this.
range is a class, and using in like e.g. range(1, a) creates an object of that class. This object is created only once, it is not recreated every iteration of the loop. That's the reason the first example will not result in an infinite loop.
The other two loops are not infinite because, unlike the range object, the loop variable i is recreated (or rather reinitialized) each iteration. The values you assign to i inside the loop will be overwritten as the loop iterates.
Consider a for loop:
for item in iterable:
print(item)
The idea is that as long as iterable is unchanged, we will loop through each and every item inside iterable once. For example,
for item in [3, 2, 1, 666]:
print(item)
will output 3 2 1 666. In particular, we find that range(1, 4) is a easy way to represent an iterable [1, 2, 3]. Thus,
for i in range(1, 4):
print(i)
will output 1 2 3.
Example 1
a=5
for i in range(1,a):
print(i)
a=a+1
In this case, range(1,a) is evaluated once, when the loop begins.
Example 2
for i in range(1,4):
print(i)
i=i-1
In this case, i is reevaluated every loop, before executing the print and i=i-1 statements within the body of the loop.
Example 3
for i in range(1,4):
print(i)
i=1
Just like Example 2, i is reevaluated every loop.
The itertools.repeat function will return an object endlessly, so you could loop over that:
import itertools
for x in itertools.repeat(1):
pass
To iterate over an iterable over and over again, you would use itertools.cycle:
from itertools import cycle
for t in cycle(range(0, 4)):
print(t)
This will print the following output:
0
1
2
3
0
1
2
3
0
1
...
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):
....
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