Skip to content Skip to sidebar Skip to footer

Why Can't "i" Be Manipulated Inside For-loop

Why does: for i in range(10): i += 1 print(i) return: 1 2 3 4 5 6 7 8 9 10 instead of: 2 4 6 8 10 ? Here would be some details if any more were necessary.

Solution 1:

for i in range(10):
    i +=1print(i)

is equivalent to

iterator = iter(range(10))
try:
    whileTrue:
        i = next(iterator)
        i += 1print(i)
except StopIteration:
    pass

The iterator that iter(range(10)) produces will yield values 0, 1, 2... 8 and 9 each time next is called with it, then raise StopIteration on the 11th call.

Thus, you can see that i gets overwritten in each iteration with a new value from the range(10), and not incremented as one would see in e.g. C-style for loop.

Solution 2:

you should use steps in your range:

for i in range(2,11,2):
    print(i)

output:

2
4
6
8
10

Solution 3:

i is assigned at each loop iteration overwriting any changes done to its value.

for i in range(10):
    i +=1print(i)

is equivalent to:

 i = 0 # first iiteration
 i += 1
 print(i)

 i = 1 # second iiteration
 i += 1
 print(i)

 i = 2 # third iiteration
 i += 1
 print(i)

 # etc up to i = 9

Post a Comment for "Why Can't "i" Be Manipulated Inside For-loop"