2

I want for loop to change its pass behavior

For example, make it jump every 3rd index to another 2 positions?

for i in range(n):
   if i % 3 == 0:
     print('found i div by 3, jump 2 positions forward')
     i = i + 2

This does not work.

It goes through every i in range from 0 to n.

Georgy
  • 12,464
  • 7
  • 65
  • 73
ERJAN
  • 23,696
  • 23
  • 72
  • 146

4 Answers4

5

You can use a while loop,

i = 0
while i < n:
   if i % 3 == 0:
     print('found i div by 3, jump 2 positions forward')
     i = i + 2
     continue
   i = i + 1
Shubham Sharma
  • 714
  • 1
  • 8
  • 18
4
  1. if you just want a step other than 1, range has a parameter for that, just call range(0, 10, 3) and it'll iterate from 0 (inclusive) to 10 (exclusive) incrementing by 3 each time rather than 1

  2. if you want to do something else and the skip condition is dynamic, don't use iterators, manage your loop manually (using a while and an explicit counter), that's what I'd recommend here

  3. alternatively to (2) you can mess with the iterator itself, a for loop desugars to:

    it = iter(range(n))
    while True:
        try:
            i = next(it)
        except StopIteration:
            break
        ...
    

    so if you get the it manually and keep a reference to it, you can call next on it explicitly to skip ahead:

    it = iter(range(n))
    for i in it:
        if i % 3 == 0:
            print('found i div by 3, jump 2 positions forward')
            next(it, None); next(it, None)
    

    I would not recommend the second style, the first one already tells the reader upfront that you're doing something weird, and it does it in a straightforward manner.

Masklinn
  • 34,759
  • 3
  • 38
  • 57
3

You can specify step-size in for loop if you want values divisible by 3

for i in range(0, n, 3):
    print(i)

Output:

0
3
6
Sociopath
  • 13,068
  • 19
  • 47
  • 75
0

We can also use the slice operator [::] to change the original range according to a condition

l= range(n)

for i in l:
    if i%3 == 0:
        print('found i div by 3, jump 2 positions forward')
        l = l[::2]
Rain
  • 3,416
  • 3
  • 24
  • 40