5

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.

1
  • Which version of Python are you using? Commented Apr 23, 2015 at 2:39

4 Answers 4

9

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]
Sign up to request clarification or add additional context in comments.

Comments

6

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.

1 Comment

To be pedantic, it returns a list in Python 2 and a range object in Python 3.
1

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

Comments

0

The for loop in python is not an iterator, but rather iterates over a sequence / generator i.e. 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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.