Search code examples
pythonloopsskip

skip every nth value when looping over a range - python


Let's say I have something like this.

for i in range((n**2)+(n-1)):
    print i,

Here

n = any integer after one(2, 3, 4 etc.)

Now, if n is 2, I'll get values of i as 0, 1, 2, 3, 4.

What I need is to be able to skip every nth value of i so that, if n is 2, my output will be 0, 1, 3, 4 and if n = 3, my output will be 0, 1, 2, 4, 5, 6, 8, 9, 10

Thank you.


Solution

  • One such way to do that is just skip the iterations of the loop you don't want to iterate with a continue statement

    for i in range(0,11):
        if i % 3 == 0 and i != 0:
            continue
        print(i)
    
    
    1
    2
    4
    5
    7
    8
    10