Jose Rodriguez
Jose Rodriguez

Reputation: 101

Using `for` in `range(x)` loop


Shouldn't both blocks of code print similar results? Why is the range function inside of the inner loop reevaluated each time the inner for statement is reached while the range function in the outerloop is only evaluated once?

x = 4
for j in range(x)
   for i in range(x)
       print i
       x = 2

Results
0
1
2
3
0
1
0
1
0
1

I know the first 4 integers printed ( 0 - 3) are a result of the code for j in range(x): code but why are the the following also printed?
0
1
0
1
0
1
The code

x = 4
for j in range(x):
    print i
    x = 5

Prints
0
1
2
3

Additional Info Python 2.7 in IDLE

Upvotes: 1

Views: 11598

Answers (5)

fiona fino
fiona fino

Reputation: 1

j is not printed, insert " print('xx', j, 'oo') " before " for i in range(x): "

then change to "print('xx', x, 'oo')

or change 'for j in range(x):' to 'for j in range(225,200,-5):' follow with 'print(j)' before 'for i in range(x):'

Upvotes: -2

Sharma
Sharma

Reputation: 1

Here is how I view it:

Inner loop is executed for each iteration of outer loop

x = 4
j = 0
for i in range (x):
    print(i)
    x = 2
j = 1
for i in range(x) # this x is no longer 4 but it is 2
    print(i)
    x = 2
j = 2
for i in range (x): # this x is, of course, 2
    print(i)
    x = 2
j = 3
for i in range (x): # this x is, of course, 2
    print(i)
    x = 2

Upvotes: 0

Jakub M.
Jakub M.

Reputation: 33827

Function range(x) produces a list of [0,1,2,3,4]. In for loop you iterate over this list.

Your code is equivalent to:

for j in [0,1,2,3]:
    for i in [0,1,2,3]:
        print i
    for i in [0,1]:
        print i
    for i in [0,1]:
        print i
    for i in [0,1]:
        print i

Upvotes: 4

stevedes
stevedes

Reputation: 46

range(x) is evaluated only once i.e. when the loop begins, that is why modifying x inside the loop has no effect.

However, in the first code clock, you change x to 2 in the inner, so the next time the inner loop is executed, range only gives (0,1).

Edit: your first block of code is equivalent to

x = 5
for i in range(x)
    print i
    x = 2

Upvotes: 0

sberry
sberry

Reputation: 132018

I can only explain by walking through the iterations of the loops, so here goes:

x = 4
for j in range(x)
   for i in range(x)
       print i
       x = 2

First time through.

x = 4
for j in [0, 1, 2, 3]
    for i in range [0, 1, 2, 3]
        print i
        x = 2

prints

0
1
2
3

Now x is set as 2, but the outer loops range has already been executed, so it is not reevaluated.

Code now becomes:

for j in [0, 1, 2, 3]:
    for i in [0, 1]:
        print i
        x = 2

prints

0
1

And this continues two more times.

Upvotes: 4

Related Questions