10.7. Nested Iteration

Nested iteration simply means that we will place one iteration construct inside of another. We will call these two iterations the outer iteration and the inner iteration. To see how this works, consider the iteration below.

i: int
for i in range(0, 5, 1):
    print(str(i))

We have seen this enough times to know that the value of i will be 0, then 1, then 2, and so on up to 4. The print will be performed once for each pass. However, the body of the loop can contain any statements including another iteration (another for statement). For example,

i: int
j: int
for i in range(0, 5, 1):
    for j in range(0, 3, 1):
        print(str(i) + " " + str(j))

The for i iteration is the outer iteration and the for j iteration is the inner iteration. Each pass through the outer iteration will result in the complete processing of the inner iteration from beginning to end. This means that the output from this nested iteration will show that for each value of i, all values of j will occur.

Here is the same example in activecode. Try it. Note that the value of i stays the same while the value of j changes. The inner iteration, in effect, is moving faster than the outer iteration.

 
1
i: int
2
j: int
3
for i in range(0, 5, 1):
4
    for j in range(0, 3, 1):
5
        print(str(i) + " " + str(j))
6

(nested1)

Another way to see this in more detail is to examine the behavior with codelens. Step through the iterations to see the flow of control as it occurs with the nested iteration. Again, for every value of i, all of the values of j will occur. You can see that the inner iteration completes before going on to the next pass of the outer iteration.

Python 3.3
1i: int
2j: int
3for i in range(0, 5, 1):
4    for j in range(0, 3, 1):
5        print(str(i) + " " + str(j))
Step 1 of 43
line that has just executed

next line to execute

Visualized using Online Python Tutor by Philip Guo
Frames
Objects

(nested2)

Check your understanding

list-24-1: What will the following nested for-loop print? (Note, if you are having trouble with this question, review CodeLens 3).

i: int
j: int
for i in range(0, 3, 1):
    for j in range(0, 2, 1):
        print(str(i) + " " + str(j))
a.

0 0
0 1
1 0
1 1
2 0
2 1

b.

0   0
1   0
2   0
0   1
1   1
2   1

c.

0   0
0   1
0   2
1   0
1   1
1   2

d.

0   1
0   1
0   1





You have attempted 1 of 4 activities on this page
Next Section - 10.8. Image Processing