0
r = [1,2,3,4,5,6,7,8,9,10,11,12,13]
for i in range(len(r)):
    print(i)
    if r[i] %2 == 0:
        print('found even')
        i+=3

It still goes through all i's and not jumps over by 3. Why is that? Is the i somehow losing its scope?

ERJAN
  • 23,696
  • 23
  • 72
  • 146
  • 2
    Because `i` is just your local variable, and the `range` iterator keeps its own internal track of which number to yield next. If you need to control the index variable yourself, use a `while` loop. – kaya3 Feb 15 '20 at 18:37
  • 1
    Because your ```i``` iterates over elements of ```range``` (which is iterator of consecutive numbers) so after you add ```3``` there it will change ```i``` and go to the next element of ```range```. Try printing ```i``` after you add ```3```, you will see what I mean – Grzegorz Skibinski Feb 15 '20 at 18:41

1 Answers1

1

for is not the correct loop, use while:

r = [1,2,3,4,5,6,7,8,9,10,11,12,13]
i = 0
while i < len(r):
    print(i)
    if r[i] % 2 == 0:
        print('found even')
        i += 3
    else:
        i += 1
Daniel
  • 42,087
  • 4
  • 55
  • 81