0

I need to decrement the loop index inside a for loop. Why doesnt the i -= 1 work?

for i in range(3):
    print(i)
    if i == 2:
        i -= 1

the output is

0
1
2

instead of

0
1
2
2
.
.

2 Answers2

1

You seem to be under the misconception that for i in range(n): ... is just syntactic sugar for this:

i=0
while i < n:
    ...  # loop body here
    i+=1

Instead the thing you're iterating over gets asked for new values every time. The real expansion is something like this:

iterator = iter(range(3))
while True:
    try:
        i = next(iterator)
    except StopIteration:
        break
    ...  # loop body here

You can see how changing i in the ... block does nothing here, because in the next loop iteration we just ask iterator (in this case a range_iterator) for a new value without respect for the new one.

L3viathan
  • 26,748
  • 2
  • 58
  • 81
0

for loop uses iterator, you cannot modify iterator in this fashion. The simplest solution is to use a while loop like :

i = 0
while i < 3:
    print(i)
    if i == 2:
        i -= 1
    i += 1
Taohidul Islam
  • 5,246
  • 3
  • 26
  • 39