简体   繁体   中英

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.

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]

no, range(x) will return a list with the items[0,1,2,3,4,5,6,7,8,9,10,11,12,13] these items will be iterated. Each time that the loop body gets evaluated x's value change but this does not affects the list that was already generate.

in other words the collection that you will be iterating will be generated only one time.

It's because python for in loop have different behavior compared to for (in other languages): range(x) is not executed in every iteration, but at first time, and then for in iterate across its elements. If you want to change the code to run an infinite loop you can use a while instead (and in that case range(x) is pointless).

The for loop in python is not an iterator, but rather iterates over a sequence / generator ie any form of iterable .

Considering this, unless the iterable is infinite, the loop will not be infinite. A sequence cannot be infinite but you can possibly create/utilite an infinite generator. One possibility is to use itertools.count which generates a non-ending sequence of numbers starting from a specified start with a specified interval.

from itertools import count        |  for(;;) {
for i in count(0):                 |      //An infinite block
    #An infinite block             |  }

Alternatively, you can always utilize while loop to create a classical infinite loop

while True:
     #An infinite block

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM