Kat
Kat

Reputation: 43

Python for loop - Can i skip an a number of iterations from condition set inside the loop?

I have a for loop that iterates through a range, but I would like it to skip a number of iterations based on a condition. This is the code:

for i in range(1,100):

    if some_condition:
        i += some_number

What I am trying to accomplish: So let's say i=5 the some_condition is triggered and some_number=2, this would set i= 7, and then the next i that we iterate to will be 8, so we never iterate through 6 and 7. How can I do this?

Upvotes: 1

Views: 92

Answers (1)

Jacob Lee
Jacob Lee

Reputation: 4700

It might be easier to use a while loop:

increment = 2

i = 1
while i < 100:
    if some_condition:
        i += increment
    i += 1

Since a for loop reassigns the iterator to the next item in the iterable, whatever you do in the for clause has no effect on the iterator the next time the loop iterates.

Upvotes: 5

Related Questions