0

can I modify range() during for loop?

for i in range(10):
    if something:
        pass
        # change range
    print(i)

An example: Let method something be i == 5 and the body will decrease range by one.

Expected output:
0
1
2
3
4
5
5
6
7
8
9

I have a little more complex range() like range(0, len(data), 1024).

Thanks for any help!

John Doe
  • 3
  • 1

3 Answers3

5

You cannot modify the generator used in the for loop during the iteration process. Instead, you could refactor your code using a while loop. For example, if your range is range(start, stop, step) (using the notation similar to that used in the Python documentation), you can write the loop as follows:

i = start
while i < stop:
    # do stuff
    i += step

This allows you to modify i however you'd like inside the while loop.

luuk
  • 1,630
  • 4
  • 12
0

Try the following:

i = 0

while i <= 5:
    print(i)
    i = i + 1
i = i - 1
while i <= 10:
    print(i)
    i = i + 1

As others have said, it is probably best to use a while loop in this scenario and manually increase your value every time the loop is performed, rather than using a for loop.

Dugbug
  • 454
  • 2
  • 11
0

You can kind of modify it within the for loop using break keyword.

start_val  = 0
stop_val = 10
for i in range(start_val ,stop_val):
    if i==5:
        start_val = 5
        print(i)
        for i in range(start_val ,stop_val):
            print(i)
        break
    print(i)

This gives expected output:

0
1
2
3
4
5
5
6
7
8
9
BetterCallMe
  • 636
  • 7
  • 15