for sets the target variable each iteration. range() provides the values for this, nothing else. You can set i inside the loop body to anything you like, but that doesn't alter what the range() sequence will produce for the next iteration.
This is what happens:
- An iterator is created for the
range(1, 11) sequence. It consists of a reference to the range object and and index, starting at 0.
- The next value is taken from the iterator,
range(1, 11)[0], producing 1
i = 1 is executed, and the loop body is started
- In the loop body,
i = i * 2 is executed, setting i to 2
i is printed, the loop body ends
- The iterator index is incremented to 1.
- The next value is taken from the iterator,
range(1, 11)[1], producing 2
i = 2 is executed, and the loop body is started
- In the loop body,
i = i * 2 is executed, setting i to 4
i is printed, the loop body ends
- The iterator index is incremented to 2.
- The next value is taken from the iterator,
range(1, 11)[2], producing 3
i = 3 is executed, and the loop body is started
- In the loop body,
i = i * 2 is executed, setting i to 6
i is printed, the loop body ends
This continues on until the loop body for range(1, 11)[9] has been processed; there is no range(1, 11)[10] so the loop ends.
At no point does setting i to a different value in the loop alter how the loop runs. You'd have to alter the iterable, the object the for loop iterates over, to alter how the loop runs:
>>> list_of_numbers = [1, 2, 3, 4]
>>> for i in list_of_numbers:
... discard = list_of_numbers.pop() # making the list shorter!
... print(i)
...
1
2
Now the loop ends early, because we removed elements from the iteratable, and the end is reached 'early'.
iis set anew from the next value in therange()sequence. You can't update it in the loop, because you are not altering the iterator.forstatement,iis set to the next up of those values (1 through 10 inclusive). As Martijn said, nothing you do inside the loop affects whichiis up next from yourrangestatement the next time through your loop.range()is not a generator. It is a sequence, just like a list or a tuple or a string. Ranges have a length, you can index into them, you ran reverse ranges.