1

I am coming from a c++ language and there if i change the value of 'i' in the loop then it affect the iteration of the loop but it is not happening in python.

for example, in c++:

for(int i=0; i<10; i++){
    cout<<i<<" ";
    if(i==5)
        i = 8;
}

in above code, as the value of 'i' reaches 5 it become 8 and after one more iteration it become 9 and then loop ends. output of the above code is-

0 1 2 3 4 5 9

but when i write the similar code in python it doesn't affect the iteration and the loop runs all 10 times.
code in python is -

for i in range(0, 10):
    if i == 5:
        i = 8
    print(i, end=" ")

the output of this code is -

0 1 2 3 4 8 6 7 8 9 

it is just changing the value of 5 to 8, and not changing the loop iteration.

how can i achieve the c++ result in python, please help!
thanks in advance :)

kuro
  • 2,585
  • 1
  • 12
  • 23
  • 1
    Does this answer your question? [Accessing the index in 'for' loops?](https://stackoverflow.com/questions/522563/accessing-the-index-in-for-loops) – Louis Go Aug 21 '20 at 05:10
  • You can always `continue` for `i` value between 6 to 8 like `if 5 < i < 9: continue` – kuro Aug 21 '20 at 05:10
  • 1
    This seems to be the same questions as [Changing the value of range during iteration in Python](https://stackoverflow.com/questions/38672963/changing-the-value-of-range-during-iteration-in-python). – Heron Yang Aug 21 '20 at 05:12

2 Answers2

1

When you say i in range(0,10) you are generating a list of [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] that you are later on iterating over, this means that the value of i is not used as an increasing int but you are rather iterating over an array.

The best solution would probably be to change from a for loop to a while loop instead.

i = 0
while i < 10:
    if i == 5:
        i = 8
    print(i)
    i += 1
JakobVinkas
  • 803
  • 3
  • 14
0

You could try a while loop:

i = 0
while i < 10:
    if i == 6:
        i = 9
    print(i)
    i += 1

Output:

0 1 2 3 4 5 9
footfalcon
  • 481
  • 3
  • 11