0

out of curiosity I wanted to see what would happen with

x=4
y=3
for y in xrange(0,y):
    print "Y---",y
    print "X---",x
    for x in xrange(0,x):
        print "x",x

this prints out

Y--- 0
X--- 4 

x 0
x 1
x 2
x 3

Y--- 1
X--- 3 

x 0
x 1
x 2

Y--- 2
X--- 2 

x 0
x 1

y progresses as expected, but x decreases - what causes this to happen?

4 Answers 4

4

Your inner loop redefines x, and so each outer loop causes it to use the last, new, smaller value for x. This makes the inner loop shorter each time.

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

Comments

1

Your variable x = 4 is referencing to x variable in the second for loop i.e for x in xrange(0,x): which are both in module level scope. So after each iteration of inner loop x is assined with a new value.

For example :

>>> x = 4
>>> for x in xrange(0, 2):
...     print x
...
0
1
>>> x
1

Comments

1

This happens because you're using x as both an input to the range to be iterated over, AND the actual counter for the loop. x retains the last value that was given to it as part of the inner loop, and by nature of xrange that would be x-1.

To see what's going on, try:

x = 10
for x in xrange(5):
    print x
print x

The final output is 4, because that was the last value that x took as part of the for loop.

If you don't want this behavior, use another variable as the counter for the inner loop. i.e.

x=4
y=3
for y in xrange(0,y):
    print "Y---",y
    print "X---",x
    for z in xrange(0,x):
        print "x",z

Comments

0

Unlike some other languages, Python loops do not introduce a new scope. This means that using x as your loop variable doesn't shadow the global x as you seem to be expecting - instead, it gets reassigned. You can see this by doing print x after the loop - it won't revert to its preloop value, but retain the value it had at the last iteration. That will also be the value it will keep at the next iteration of the outer loop. You can see the same thing more clearly by using a loop variable that didn't exist before the loop: if the loop created a new scope, attempting to print that variable would be a NameError, but it isn't.

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.