Skip to main content
Engineering LibreTexts

4.2: Nested for Loops

  • Page ID
    13577
  • One concept that you will see in Memory Puzzle (and most of the games in this book) is the use of a for loop inside of another for loop. These are called nested for loops. Nested for loops are handy for going through every possible combination of two lists. Type the following into the interactive shell:

    >>> for x in [0, 1, 2, 3, 4]:
             for y in ['a', 'b', 'c']:
                 print(x, y)
                 
    0 a
    0 b
    0 c
    1 a
    1 b
    1 c
    2 a
    2 b
    2 c
    3 a
    3 b
    3 c
    4 a
    4 b
    4 c
    >>>
    

    There are several times in the Memory Puzzle code that we need to iterate through every possible X and Y coordinate on the board. We’ll use nested for loops to make sure that we get every combination. Note that the inner for loop (the for loop inside the other for loop) will go through all of its iterations before going to the next iteration of the outer for loop. If we reverse the order of the for loops, the same values will be printed but they will be printed in a different order. Type the following code into the interactive shell, and compare the order it prints values to the order in the previous nested for loop example:

    >>> for y in ['a', 'b', 'c']:
            for x in [0, 1, 2, 3, 4]:
                print(x, y)
    
    0 a
    1 a
    2 a
    3 a
    4 a
    0 b
    1 b
    2 b
    3 b
    4 b
    0 c
    1 c
    2 c
    3 c
    4 c
    >>>