Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify range variable in for loop (python)

Tags:

python

range

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.

like image 971
Vikas Goel Avatar asked Oct 27 '25 00:10

Vikas Goel


1 Answers

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

like image 180
Aasmund Eldhuset Avatar answered Oct 28 '25 16:10

Aasmund Eldhuset



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!