3

I try to skip several steps in for loop like while loop.

In the while loop, the steps are adjusted to specific conditions as shown in the code below.

i = 0 
while i <10:
    if i == 3:
        i = 5
    else:
        print(i)
    i = i + 1
#result 0 1 2 6 7 8 9

However, I tried to adjust the steps of the for loop in the same way, but failed.

for i in range(10):
    if i == 3:
        i = 5
    else:
        print(i)
#result 0 1 2 4 5 6 7 8 9

Can't I control step 'i' directly in a for loop?

If there is a way, let me know and I would appreciate it.

송준석
  • 991
  • 1
  • 16
  • 32

5 Answers5

6

Changing i in the loop body has no effect, as it will be automatically assigned the "next value in the range() result" on each iteration. You can instead use continue on values that you want to skip:

for i in range(10):
    if 3 <= i <= 5:
        continue
    else:
        print(i)
soulmerge
  • 73,842
  • 19
  • 118
  • 155
3

No, you can't. On every new iteration of the loop, the i variable in the for i in range(10) statement gets reevaluated.

Hannes Ovrén
  • 21,229
  • 9
  • 65
  • 75
1

While @soulmerge's answer works, it can be inefficient if the number of iterations you want to skip is overly large, in which case you can build the exact sequence you want to iterate over instead:

for i in (*range(3), *range(6, 10)): # imagine the case of (*range(3), *range(996, 1000))
    print(i)

or more efficiently, use itertools.chain to avoid building a tuple first:

from itertools import chain
for i in chain(range(3), range(6, 10)):
    print(i)
blhsing
  • 91,368
  • 6
  • 71
  • 106
0

I'm not sure if I understood your question but maybe you are looking for continue statement

While i < 10 :
    if i == 4 or i == 3 :
        continue

In this code you skip the loop when i = 4 or 3

Adel gamer
  • 23
  • 7
  • I think you have mistaken `pass` for `continue`: The former statement will just be ignored by the interpreter, while the latter will cause the loop to "enter its next cycle". See here: https://stackoverflow.com/a/9484008/44562 – soulmerge Nov 18 '19 at 08:23
0

In C i is a variable that gets incremented at the end of the for loop and you can change it yourself, however in Python a for loop operates like a foreach loop from other languages where a generator produces results and the next result is used for each iteration.

In this case, if you needed to use a for(each) loop, you would use continue to skip over the iterations you wanted to miss:

if i >= 3 and i <= 5:
    continue

Remember, for and foreach loops are just syntactic sugar for a while loop, which in the end is really syntactic sugar for goto label (and yes there are some language exceptions to this, but ultimately assembly is goto)

Michael
  • 810
  • 6
  • 18