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(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.

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.

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
    
  • Output a
  • i will start with a value of 0 and then j will iterate from 0 to 1. Next, i will be 1 and j will iterate from 0 to 1. Finally, i will be 2 and j will iterate from 0 to 1.
  • Output b
  • The inner for-loop controls the second digit (j). The inner for-loop must complete before the outer for-loop advances.
  • Output c
  • The inner for-loop controls the second digit (j). Notice that the inner for-loop is over the list [0, 1].
  • Output d
  • The outer for-loop runs 3 times (0, 1, 2) and the inner for-loop runs twice for each time the outer for-loop runs, so this code prints exactly 6 lines.
You have attempted of activities on this page
10.6. Nested Lists"> 10.8. Image Processing">Next Section - 10.8. Image Processing