+ 2

Updating *for* loop counter in the loop block

Well, I was thinking in these lines: for i in range(6): print(i) if i==2: i=4 I expected the output to be 1 2 5 But instead I got 1 2 3 4 5 What is happening here? Can for loop variable be not uprated in loop block like while loop? Is there any other way to update loop counter in for loop (than continue each time you want to skip it)? P. S. I've tried it only in Playground, not in real Python.

11th Jul 2016, 12:16 PM
Jesse P Francis
Jesse P Francis - avatar
3 ответов
+ 2
There is a bag with 6 balls labeling from 1 to 6. You sequentially pick up the 6 balls according to their number. Every time, when you pick up a ball, you show the ball number to your friend Bob. But there is one exception, when you get the ball 2, you show it to Bob, then throw it and receive a ball labeled 4 from maybe your girl friend. Finally, the question is, what numbers will Bob see? The key point is that, the new ball 4 getting from your girl friend does not affect what the next ball you pick up.
11th Jul 2016, 1:29 PM
df32
df32 - avatar
+ 2
your changes to the i variable do not have effect because i gets new value from the list at the beginning of each iteration. the condition for loop end is not the variable value, but the number of iterable elements you have gone through. so for does not behave like for in languages like java or c, but rather like foreach. so i cannot think of a nice way to do that with for except maybe making a list without 3 and 4 and using it instead of range.
11th Jul 2016, 1:30 PM
RedAnt
RedAnt - avatar
+ 2
for in range is like foreach loop you are iterating in object not on variable, so I=4 does not affect your object.ie range.
13th Jul 2016, 6:02 AM
Suryaprakash Tiwari
Suryaprakash Tiwari - avatar