Alex Rivera | Logout

Why doesn't modifying the iteration variable affect subsequent iterations?

Asked 2013-03-12T13:53:29.437
60

Here's the Python code I'm having problems with:

for i in range (0,10):
    if i==5:
        i+=3
    print i

I expected the output to be:

0
1
2
3
4
8
9

However, the interpreter spits out:

0
1
2
3
4
8
6
7
8
9

I know that a for loop creates a new scope for a variable in C, but have no idea about Python. Why does the value of i not change in the for loop in Python, and what's the remedy to it to get the expected output?


See How to modify list entries during for loop? for how to modify the original sequence. In 3.x, of course, range creates an immutable object, so it would still not work.

Edit
Report

1 Answer

1

Python's for loop simply loops over the provided sequence of values — think of it as "foreach". For this reason, modifying the variable has no effect on loop execution.

This is well described in the tutorial.

answered 2013-03-12T13:56:40.593

Your Answer