Nested For Loops

Outside Resources:

Blog post – nested loops with lists and if statements


Loops can be inside other loops.

Nesting is when a code structure is inside another structure.

Example of nested loops:

print('x | y')
for x in range(3):   #outer loop
    print('-----')
    for y in range(5):   #inner loop
        print(x,"|", y)

The program’s output is shown below.

The outer loop repeats three times. The inner loop repeats five times for each iteration of the outer loop, for a total of 15 repeats.

Output:

x | y
-----
0 | 0
0 | 1
0 | 2
0 | 3
0 | 4
-----
1 | 0
1 | 1
1 | 2
1 | 3
1 | 4
-----
2 | 0
2 | 1
2 | 2
2 | 3
2 | 4

Notes:

  • The inner and outer variables must use different variables.
  • The loops could be for loops or while loops.
  • Pay attention to indents, because this determines if a command is in the inner loop, outer loop, or neither.