How to change index of a for loop?

For your particular example, this will work:

for i in range(1, 10):
    if i in (5, 6):

However, you would probably be better off with a while loop:

i = 1
while i < 10:
    if i == 5:
        i = 7
    # other code
    i += 1

A for loop assigns a variable (in this case i) to the next element in the list/iterable at the start of each iteration. This means that no matter what you do inside the loop, i will become the next element. The while loop has no such restriction.

Leave a Comment