My Question is:
Why it works for the inner loop, but not the outer one?
NOT
how to write something to do this job... I know it is not a safe solution to change list dynamically in loop.
Code 1:
list_a = [1,2,3]
list_b = [11,12,13]
for i in list_a:
for j in list_b:
print(i, j)
Result 1:
1 11
1 12
1 13
2 11
2 12
2 13
3 11
3 12
3 13
Code 1
is a two-level nested loop for printing combination of two list, and it works as expected.
I want to change the list dynamically during the loop. By changing the list that trigger the looping, I expect the looping behavior is also changed dynamically.
Code 2:
list_a = [1,2,3]
list_b = [11,12,13]
for i in list_a:
list_a = [100, 200]
for j in list_b:
print(i, j)
Code 3:
list_a = [1,2,3]
list_b = [11,12,13]
for i in list_a:
for j in list_b:
list_a = [100, 200]
print(i, j)
Result 2/3:
1 11
1 12
1 13
2 11
2 12
2 13
3 11
3 12
3 13
Code 2
and Code 3
is for changing the first list. Although list_a is updated in the first step of the loop, the looping behavior of outer for loop
dose not change.
Code 4:
list_a = [1,2,3]
list_b = [11,12,13]
for i in list_a:
for j in list_b:
list_b = [100, 200]
print(i, j)
Result 4:
1 11
1 12
1 13
2 100
2 200
3 100
3 200
Code 4
is for changing the second list. list_b is updated in the first step of the loop, and the looping behavior of the inner one is affected.