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().

Answer from John La Rooy on Stack Overflow
🌐
Python.org
discuss.python.org › ideas
"for i in range()" to do an infinite loop with a counter - Ideas - Discussions on Python.org
August 10, 2022 - Hi, Usually in Python we can avoid the i = 0 … i += 1 paradigm that we use in other languages when we need to count things, thanks to enumerate(...), for i in range(100), etc. Along the years I have nearly always found a more “pythonic” ...
Discussions

[Thought experiment] Achieving one-line infinite loops in Python
One-liner infinite print loop, that doesn't use while, append, etc.: for i in __import__('itertools').count(): print(i) More on reddit.com
🌐 r/learnpython
15
5
September 5, 2018
Infinite loops using 'for' in Python - Stack Overflow
This loop will indeed run infinitely. ... This will however easily run out of memory. Furthermore some collections (not lists) will raise an exception for good reasons when altering a collection when iterating over it. 2018-01-11T12:07:45.473Z+00:00 ... Sure. It's not meant for actual "use", just for creating a counter-example which behaves as OP expected. 2018-01-11T12:08:35.727Z+00:00 ... Because a range is either a list (Python2... More on stackoverflow.com
🌐 stackoverflow.com
January 11, 2018
Allow `range(start, None, step)` for an endless range - Ideas - Discussions on Python.org
Currently, to iterate over finite ... as in: for i in range(10): print(i) For an infinite arithmetic sequence, there are a few approaches. One can replace the ‘10’ with a long sequence of nines, write a generator function or just switch to a while loop, but the current ‘best’ ... More on discuss.python.org
🌐 discuss.python.org
0
January 15, 2021
How do I make an infinite for loop in Python (without using a while loop)? - Stack Overflow
Is there way to write an infinite for loop in Python? for t in range(0,10): if(t == 9): t= 0 # will this set t to 0 and launch infinite loop? No! print(t) Generally speaking, is there way to More on stackoverflow.com
🌐 stackoverflow.com
April 29, 2016
🌐
The Python Coding Stack
thepythoncodingstack.com › p › infinite-for-loop-infinite-iterator-python
To Infinity and Beyond • The Infinite `for` Loop
March 7, 2024 - You can import itertools and update ... an infinite animation. The for loop iterates through all_positions, but all_positions is an infinite iterator....
🌐
Learning About Electronics
learningaboutelectronics.com › Articles › How-to-create-an-infinite-for-loop-in-Python.php
How to Create an Infinite For Loop in Python
Using the the range() function in Python, we can set up a range that goes from one value to a certain value, such as 1 to 3, and then have this repeat infinitely using the cycle() function from the itertool module. This way, we can create an infinite loop between a certain range in Python.
🌐
Reddit
reddit.com › r/learnpython › [thought experiment] achieving one-line infinite loops in python
r/learnpython on Reddit: [Thought experiment] Achieving one-line infinite loops in Python
September 5, 2018 -

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.

🌐
LinkedIn
linkedin.com › pulse › while-loops-infinite-range-function-python-baha-yaf9f
while loops, infinite loops, for loops, and the range function - Python
October 28, 2024 - The first time it is run, the variable i is set to 0. After Python finishes an iteration through all the code inside the for loop’s clause, the execution goes back to the top of the loop, and the for statement increments i by one. This is why range(5) results in five iterations through the clause, with i being set to 0, then 1, then 2, then 3, and then 4.
Find elsewhere
🌐
Quora
quora.com › Can-the-for-loop-be-used-to-create-an-infinite-loop-in-Python
Can the for loop be used to create an infinite loop in Python? - Quora
Just keep adding to the iterable that feeds your loop. For example: [code]iterable = ['the', 'end', 'is', 'never'] for word in iterable: print(word) iterable.append(word) [/code]However, this ...
🌐
Sololearn
sololearn.com › en › Discuss › 1442089 › can-the-range-function-in-python-be-used-to-make-an-infinite-range-if-yes-how
Can the range() function in python be used to make an infinite range? If yes, how? | Sololearn: Learn to code for FREE!
I want to create a range from 0 to infinity. How can I do it with range(), or please tell some other way by which it can be done. ... No, range() can't. But itertools.count() can. For your problem, you could do from itertools import count for i in count(): do_something_with(i) You can also specify from which number you want it to start counting and by how many steps you want it to increment each time.
🌐
Python.org
discuss.python.org › ideas
Allow `range(start, None, step)` for an endless range - Ideas - Discussions on Python.org
January 15, 2021 - Currently, to iterate over finite arithmetic sequences of integers, range is used, as in: for i in range(10): print(i) For an infinite arithmetic sequence, there are a few approaches. One can replace the ‘10’ with a long sequence of nines, write a generator function or just switch to a while loop, but the current ‘best’ way is using itertools: import itertools for i in itertools.count(): print(i) There are a few downsides to this.
🌐
Programiz
programiz.com › python-programming › looping-technique
Python Looping Techniques
# An example of infinite loop # press Ctrl + c to exit from the loop while True: num = int(input("Enter an integer: ")) print("The double of",num,"is",2 * num) ... Enter an integer: 3 The double of 3 is 6 Enter an integer: 5 The double of 5 is 10 Enter an integer: 6 The double of 6 is 12 Enter ...
🌐
Quora
quora.com › In-Python-how-do-I-set-the-range-of-a-for-loop-to-repeat-until-a-break-is-reached
In Python, how do I set the range of a for loop to repeat until a break is reached? - Quora
... I've used Python 2 and 3, and ... loop - for example using “while true” with a condition in the loop which tests for the exit condition and calls “break” when the condition is met....
🌐
StudySmarter
studysmarter.co.uk › computer science › computer programming › python infinite loop
Python Infinite Loop: Creation, Example & Error | StudySmarter
August 10, 2023 - Here's an example illustrating an infinite 'for' loop using the 'range()' function: from itertools import count for i in count(): if i > 5: break print("Value of i: ", i)In this example, the loop keeps running and printing the value of 'i' until it reaches a value greater than 5. At that point, the loop is terminated by the 'break' statement. Sometimes, it is necessary to pause the execution of a Python infinite loop for a specified duration, ensuring that the process does not consume too many resources or overwhelm the system.
🌐
Towards Data Science
towardsdatascience.com › home › latest › 3 infinite iterators in python
3 Infinite Iterators in Python | Towards Data Science
January 21, 2025 - However, when we don’t need that ... rounds, the repeat iterator will be a better solution in terms of the performance. We can see that using the repeat() function is 2x faster than the range() function....
🌐
Python.org
discuss.python.org › ideas
"for i in range()" to do an infinite loop with a counter - #13 by ncoghlan - Ideas - Discussions on Python.org
August 17, 2022 - Serhiy’s comment here is the key conceptual reason unbounded ranges aren’t allowed: they’re defined as memory efficient computed sequences rather than consumable iterators, so they’re expected to have a lower and upper bound, even though those limits might be large.
🌐
Study.com
study.com › computer science courses › computer science 113: programming in python
Infinite Loops in Python: Definition & Examples - Lesson | Study.com
July 18, 2024 - The code here produces the same result as the previous finite loop example using for: ... An infinite loop, on the other hand, is characterized by not having an explicit end, unlike the finite ones exemplified previously, where the control variable i clearly went from 0 to 9 (note that at the end i = 10, but that value of i wasn't printed). In an infinite loop the control is not explicitly clear, as in the example appearing here:
🌐
Better Programming
betterprogramming.pub › over-engineering-the-infinite-loop-in-python-53450cb52132
Over-Engineering the Infinite Loop in Python | by Nicholas Obert | Better Programming
September 20, 2023 - The most Pythonic approach to an infinite loop is to use a while loop with a constantly-true literal value simply: True. Very straightforward, isn't it? But it’s also boring at the same time.
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-loop-through-a-range
Python - Loop Through a Range - GeeksforGeeks
July 23, 2025 - In this article, we will explore the different ways to loop through a range in Python, demonstrating how we customize start, end, and step values, as well as alternative methods for more advanced use cases like looping through floating-point ranges or infinite sequences.