How to jump some steps when use python's for statement

Question:

I have an interveiw yesterday, when I write python code to achieve some algorithm, I have a question. Some logic can be achieved like this using C:

void get_some_num(int a[], int length) {       
   int i;
   for(i = 0; i < length - 1; ++i) {
       if(something) i++; // jump a num in the array
       a[i] = 1;
   }
    return some_num;
 }

C language can jump some elements(such as n) when using i += n statement in for-loop to iterate an array, but I find it’s difficult to achieve by using python’s for statement gracefully.

How can I do it?

Asked By: chyoo CHENG

||

Answers:

Python also supports continue to “skip steps” and continue the loop.

Using it in a for loop:

for i in range(0, 10):
    if i == 5:
        continue
    # will never print 5
    print(i)

if you are looking to make it skip a few indexes in your iteration, then you can do something like this with a while loop:

x = range(0, 10)
i = 0
while i <= len(x):
    if i == 5:
        i += 3
        continue
    print(i)
    i += 1

Output:

0
1
2
3
4
8
9
10
Answered By: idjaw

If you want to do this in a way similar to C, then just use a while loop (any for loop is really just a specialization of a while loop after all):

i = 0
end = 10

while i < end:
    # NOTE: do something with i here

    if i == 5:
        i += 3
    i += 1

Or you can explicitly create and move forward the iterator (which I find a lot less readable):

it = iter(range(0, 10))

for i in it:
    if i == 5:
        for j in range(0, 3):
            i = next(it)
    print(i)
Answered By: eestrada

I’ve never really had much need to skip more than one step, but… You can use a skip variable that you decrement every time you skip.

skip = 0
for i, item in enumerate(my_list[:-1]):
    if skip:
        skip -= 1
        continue
    if item == my_list[i+1]:
        skip = 1   # or whatever n value you want
        continue
    # Other code
Answered By: zehnpaard

If you want to do several jumps use the mod operator %

i.e

Jump every 2

for i in range(1, 10):
if i%2 == 0:
    print(i)

2
4
6
8

jump every 3

for i in range(1, 10):
    if i%3 == 0:
        print(i)

3
6
9

An so on.

You have to use continue

for item in loop:
    if item == 'wrong':
        continue
Answered By: user18672350
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.