2

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.

Coder
  • 1,415
  • 2
  • 23
  • 49

4 Answers4

4

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).

Aasmund Eldhuset
  • 37,289
  • 4
  • 68
  • 81
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]
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
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.

Raul R.
  • 186
  • 1
  • 12
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]