Looping from 1 to infinity in Python
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()
. Infinite loops using 'for' in Python
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.
Infinite for loop in Python like C++
Python's for
statement is a "for-each" loop (sort of like range-for in C++11 and later), not a C-style "for-computation" loop.
But notice that in C, for (;;)
does the same thing as while (1)
. And Python's while
loop is basically the same as C's with a few extra bells and whistles. And, in fact, the idiomatic way to loop forever is:1
while True:
If you really do want to write a
for
loop that goes forever, you need an iterable of infinite length. You can grab one out of the standard library:2for _ in itertools.count():
… or write one yourself:def forever():
while True:
yield None
for _ in forever():
But again, this isn't really that similar to for (;;)
, because it's a for-each loop.1.
while 1:
used to be a common alternative. It's faster in older versions of Python, although not in current ones, and occasionally that mattered.2. Of course the point of count
isn't just going on forever, it's counting up numbers forever. For example, if enumerate
didn't exist, you could write it as zip(itertools.count(), it)
.
Infinity loop issue using for loops
Now that you've shown the full code, your problem is obvious. Your original example didn't show the issue because you didn't include all relevant code. Here's your example with the relevant code that's causing the issue:
for us_code in us_code_list:
for macd_diff in macd_diff_list:
for profit_target in profit_target_list:
for stop_loss in stop_loss_list:
... # irrelevant code not shown
macd_diff_list.append(macd_diff)
The issue is that you're looping through each item in macd_diff_list
, but then for each loop iteration, you add an item to that list. So of course the loop will be infinite. You need to be looping through a different list, or adding items to a different list. Easy way to keep counting up infinitely
Take a look at itertools.count().
From the docs:
count(start=0, step=1)
--> count objectMake an iterator that returns evenly spaced values starting with
n
.
Equivalent to:
def count(start=0, step=1):
# count(10) --> 10 11 12 13 14 ...
# count(2.5, 0.5) -> 2.5 3.0 3.5 ...
n = start
while True:
yield n
n += step
So for example:import itertools
for i in itertools.count(13):
print(i)
would generate an infinite sequence starting with 13, in steps of +1. And, I hadn't tried this before, but you can count down too of course:for i in itertools.count(100, -5):
print(i)
starts at 100, and keeps subtracting 5 for each new value ....Why is my while function causing an infinite loop?
Because your I never actually increases in this while loop. If you really want to do it this way you can just add a i += 1 to the end of your function
def double_values_in_list ( ll ):
i = 0
while (i<len(ll) ):
ll[i] = ll[i] * 2
print ( "ll[{}] = {}".format( i, ll[i] ) )
i += 1
return ll
print(double_values_in_list([1, 2]))
However, this is a lot of extra steps that you don't need to take, you can simply run a pythonic for loop to make things a lot easier on yourselfdef double_values_in_list (ll):
return [x*2 for x in ll]
print(double_values_in_list([1, 2]))
Python for loop in enumerate list goes for infinite
You can iterate over a copy of this list:
for index, item in enumerate(a.copy()):
Related Topics
Get the String Within Brackets in Python
Python Pandas Dataframe, Is It Pass-By-Value or Pass-By-Reference
Cannot Redirect Output When I Run Python Script on Windows Using Just Script's Name
How to Calculate the Inverse of the Normal Cumulative Distribution Function in Python
How to Tell Pycharm What Type a Parameter Is Expected to Be
How to Skip Iterations in a Loop
Python Socket Receive - Incoming Packets Always Have a Different Size
Python MySQL Connector - Unread Result Found When Using Fetchone
How to Avoid Infinite Recursion with Super()
How to Convert a List into a String with Spaces in Python
How to Handle Exceptions in a List Comprehensions
Cartesian Product of a Dictionary of Lists
Range Over Character in Python
Syntaxerror: Unexpected Eof While Parsing