4

I am not sure why python would show this behavior:

for x in range(5):
    print "Before: ",x
    if x<3:
        x-=1
    print "After:  ",x

I get the output as:

Before:  0
After:   -1
Before:  1
After:   0
Before:  2
After:   1
Before:  3
After:   3
Before:  4
After:   4

I was not expecting it to change the value of x to 1, after I reduce it to -1 in the first iteration. Alternatively, is there a way to achieve the desired behavior when I want to alter the value of range variable?

Thanks.

3
  • Perhaps you should explain what problem you are trying to solve by altering the value of the range variable. Commented Mar 17, 2016 at 3:56
  • I think you want a while loop. Commented Mar 17, 2016 at 3:59
  • Does this answer your question? Scope of python variable in for loop Commented Dec 28, 2020 at 4:39

4 Answers 4

5

A for loop in Python doesn't care about the current value of x (unlike most C-like languages) when it starts the next iteration; it just remembers the current position in the range and assigns the next value. In order to be able to manipulate the loop variable, you need to use a while loop, which doesn't exert any control over any variables (it just evaluates the condition you give it).

Sign up to request clarification or add additional context in comments.

1 Comment

Could you elaborate on the while loop approach? My for-loop answer worked fine
4

I am not sure why python would show this behavior

Because x is reset every iteration of the loop.

If you would like to modify the range, you need to save it to a variable first, and then modify

e.g. in Python2

my_range = range(5) # [0, 1, 2, 3, 4]
for i,x in enumerate(my_range):
    print "Before: ", my_range[i]
    if x < 3:
        my_range[i] = x-1
    print "After:  ", my_range[i]

print my_range # [-1, 0, 1, 3, 4]

2 Comments

this will not work in python 3.6. it throw TypeError: 'range' object does not support item assignment error
list(range(5)) should be clear to anyone who knows the differences
1
for x in range(5):

is the same as:

for x in [0, 1, 2, 3, 4]:

in each cycle iteration x get a new value from the list, it can't be used as C, C#, Java, javascript, ... usual for, I agree with @aasmund-eldhuset that a while loop will do better what you want.

Comments

0

For python 3.6 this will work

my_range = list(range(5)) # [0, 1, 2, 3, 4]
for i,x in enumerate(my_range):
    print ("Before: ", my_range[i])
    if x < 3:
       my_range[i] = x-1
    print ("After:  ", my_range[i])

print (my_range)

You will get out as

Before:  0
After:   -1
Before:  1
After:   0
Before:  2
After:   1
Before:  3
After:   3
Before:  4
After:   4
[-1, 0, 1, 3, 4]

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.