Coder
Coder

Reputation: 1899

Modify range variable in for loop (python)

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.

Upvotes: 3

Views: 8539

Answers (4)

Mahendra S. Chouhan
Mahendra S. Chouhan

Reputation: 545

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]

Upvotes: 0

OneCricketeer
OneCricketeer

Reputation: 191701

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]

Upvotes: 4

Raul R.
Raul R.

Reputation: 196

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.

Upvotes: 1

Aasmund Eldhuset
Aasmund Eldhuset

Reputation: 37950

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

Upvotes: 4

Related Questions