Search code examples
pythonloopscontinue

Understanding errors in attempts to skip N iterations of a loop


I want to skip 3 iterations of a loop, and made various attempts.

I would like to know how to do it correctly, but more than that, I would like to understand why each of these attempts fail in different ways. Please can you explain?

These numbers are only examples. How I really use it. Your list might be ["donut", "carrot", "apple", "apple", "burger"] and when you get to carrot you discover that you have to skip two items (a dog eats two of your food items) so that your iterations should be ["donut", "apple", "burger"]. So you don't know in advance which iterations to skip. You just get a condition and number of iterations to skip.

NUMBER 1. This does not skip any iterations at all.

l = list(range(10))

for i in l:
    if i == 3:
        for j in range(3):
            continue
    print(i)

NUMBER 2. This skips some iterations, repeats an iteration, mixes up some iterations, really a total mess.

l = list(range(10))

for i in l:
    
    if i == 3:
        l.pop(i)
        l.pop(i+1)
        l.pop(i+2)

    print(i)

NUMBER 3. This skips only one iteration.

l = list(range(10))

for i in l:
    if i == 3:
        continue
        continue
        continue
    print(i)

NUMBER 4. This gives syntax error.

l = list(range(10))

for i in l:
    if i == 3:
        continue 3
    print(i)

NUMBER 5. This skips all remaining iterations.

l = list(range(10))

countdown = 0

for i in l:

    if i == 3:
        countdown = 3

    if countdown > 0:
        cuntdown = countdown - 1
        continue

    print(i)

What is going wrong in each case, and what else can I try?


Solution

  • Your code for number 5 would work except, amusingly, you have written cuntdown instead of countdown in your second if statement.

    Here is why the others do not work:

    Number 1: Continue only moves your code onto the next iteration of the loop that is currently being executed. In this example, it simply moves onto the next loop of for j in range(3): rather than for i in l so no iterations of the original loop are skipped.

    Number 2: Here you are popping elements of a list whilst iterating over it. This is not really ever advisable as you will end up with an index error or something similar.

    Number 3: This only skips one iteration because once your first Continue is executed, the loop immediately moves onto loop with i == 4 and the remaining Continues are never executed.

    Number 4: Continue 3 is not correct syntax for use with Continue