Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python for loop - why does this not infinite loop?

Consider the following snippet of Python code:

x = 14
for k in range(x):
    x += 1

At the end of execution, x is equal to 28.

My question: shouldn't this code loop forever? At each iteration, it checks if k is less than x. However, x is incremented within the for loop, so it has a higher value for the next comparison.

like image 885
Ryan Avatar asked Apr 23 '15 02:04

Ryan


People also ask

Can a for loop in Python be infinite?

We can create infinite loops in Python via the while statement. In a loop, the variable is evaluated and repeatedly updated (while the given condition is True). We can create an infinite loop in Python if we set the condition in a way that it always evaluates to True.

Can FOR loops cause infinite loops?

A for loop is only another syntax for a while loop. Everything which is possible with one of them is also possible with the other one. Any for loop where the termination condition can never be met will be infinite: for($i = 0; $i > -1; $i++) { ... }

Is for loop infinite?

One of the most common infinite loops is when the condition of the while statement is set to true. Below is an example of code that will run forever. Another classic example will be of the for loop where the terminating condition is set to infinity.

How do you make a for loop infinite?

To make an infinite loop, just use true as your condition. true is always true, so the loop will repeat forever.


1 Answers

range(x) is not a "command". It creates a range object one time, and the loop iterates over that. Changing x does not change all objects that were made using it.

>>> x = 2
>>> k = range(x)
>>> list(k)
[0, 1]
>>> x += 1
>>> list(k)
[0, 1]
like image 128
Jayanth Koushik Avatar answered Oct 13 '22 01:10

Jayanth Koushik