0

I found a behaviour in Python which is slightly counter-intuitive (or rather not what I am used to!). So, I have some code as follows:

for c in range(10):
    c += 1
    print(c)

This prints

1
2
3
4
5
6
7
8
9
10

Even doing something like:

c = 0
for c in range(10):
   ...

Does not change the output? I guess the scoping rules are different than C++. My question is if someone needs to change the loop index within the function body, how could one do it?

3
  • 3
    c is set from the range object at the top of each loop. If you don't want that, use another kind of loop, like a while loop, and increment the variable manually. It might make your code clearer anyway. Commented Apr 5, 2018 at 13:32
  • 2
    Could you elaborate what you were actually expecting? Commented Apr 5, 2018 at 13:37
  • @nautical Was expecting 1, 3, 5, 7, 9 Commented Apr 5, 2018 at 13:41

2 Answers 2

3

The for statement is a form of assignment; after the body is executed, a new value is assigned to c, overwriting any changes you may have made in the body. That is, the loop

for c in range(10):
    c += 1
    print(c)

is equivalent to

itr = iter(range(10))
while True:
    try:
        c = next(itr)
    except StopIteration:
        break
    c += 1
    print(c)

If you want to be able to modify c, you need to use a while loop:

c = 0
while c < 10:
    ...  # Arbitrary code, including additional modifications of c
    c += 1  # Unconditionally increase c to guarantee the loop eventually ends
Sign up to request clarification or add additional context in comments.

Comments

1

You can't change the loop index in Python using a for loop. It will reset back every loop as chepner explained in his answer.

You could, however, write it using a step (3rd variable of range). To insert step you need to pass start and end too.

for c in range(1,10,2): # start, end (not included), step
    print(c)

# 1,3,5,7,9

for c in range(9,0,-2): 
    print(c)

# 9,7,5,3,1

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.