Can you explain how the nested for loop behaves in figure 1?
x = 4
for j in range(x)
for i in range(x)
print(i)
x = 2
Fig.1
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
Thus showing that changing the value x inside the for loop has no impact on the number of iterations. The arguments in the range function are evaluated just before the first iteration of the loop, and not reevaluated for subsequent iterations.
Why then does x change to 2 for the nested loop in figure 1?
Another similar program:
num_list = [1, 2, 3]
alpha_list = ['a', 'b', 'c']
for number in num_list:
print(number)
for letter in alpha_list:
print(letter)
Outputs
1 #outer loop
a #nested loop
b #nested loop
c #nested loop
2 #outer loop
a #nested loop
b #nested loop
c #nested loop
3 #outer loop
a #nested loop
b #nested loop
c #nested loop
So I would expect figure 1's output to be:
0 #outer loop
0 #Nested loop
1 #Nested loop
2 #Nested loop
3 #Nested loop
1 #outer loop
0 #Nested loop
1 #Nested loop
2 #Nested loop
3 #Nested loop
2 #outer loop
0 #Nested loop
1 #Nested loop
2 #Nested loop
3 #Nested loop
3 #outer loop
0 #Nested loop
1 #Nested loop
2 #Nested loop
3 #Nested loop
Additional Info Python 3.5 in Spyder
Not exactly. In your first example, with the nested for-loop, it does have an impact on the number of iterations. It's true that once a
rangeobject is constructed, making changes to any of the variables you used to construct it will have no effect on therangeobject - however, in the nested loop, you aren't just creating tworangeobjects. You are creating one for the outer loop, and then a newrangeobject for the inner for-loop for each iteration of the outer loop.