Nested Loops in Python

A nested loop is a loop inside another loop. See exactly what order the lines run in, how to work with grids and nested lists, and how to break out of both loops.

5 min read

A nested loop is a loop inside another loop. For every single pass of the outer loop, the inner loop runs from start to finish.

pythonpython
for row in range(1, 4):
    for col in range(1, 3):
        print(row, col)
texttext
1 1
1 2
2 1
2 2
3 1
3 2

The outer loop runs 3 times and the inner loop runs 2 times for each of those, so the print line runs 3 x 2 = 6 times.

How to read a nested loop

Think of a clock. The hour hand is the outer loop and the minute hand is the inner loop: the minute hand goes all the way round before the hour hand moves one step.

Step by step, Python does this:

  1. The outer loop sets row to 1.
  2. The inner loop runs completely: col is 1, then 2.
  3. The inner loop ends, and control returns to the outer loop.
  4. The outer loop sets row to 2, and the inner loop starts again from the beginning.

The inner loop restarts every time. Its variable does not carry on from where it stopped.

Example: a multiplication table

pythonpython
for a in range(1, 4):
    for b in range(1, 4):
        print(a * b, end="\t")
    print()
texttext
1	2	3
2	4	6
3	6	9

end="\t" makes print finish with a tab instead of a new line, so the results of one row stay on the same line. The empty print() belongs to the outer loop, so it runs once per row and starts the next line.

Indentation decides which loop a line belongs to. Move print() four spaces to the right and it becomes part of the inner loop, which puts every number on its own line.

Example: printing a pattern

The inner loop can depend on the outer loop's variable:

pythonpython
for row in range(1, 5):
    for _ in range(row):
        print("*", end="")
    print()
texttext
*
**
***
****

On row 1 the inner loop runs once, on row 2 twice, and so on. In real code print("*" * row) does the same without an inner loop, but the pattern is a good way to see how the two loops interact.

Loop over a nested list

Nested loops are the natural fit for data with two levels, such as a list of lists:

pythonpython
grid = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9],
]
 
total = 0
 
for row in grid:
    for value in row:
        total += value
 
print(total)  # 45

The outer loop takes one row at a time. The inner loop takes one value at a time from that row. For more on this structure, see nested lists in Python.

Every combination of two lists

pythonpython
sizes = ["S", "M"]
colors = ["red", "blue", "green"]
 
for size in sizes:
    for color in colors:
        print(size, color)

This prints all six combinations, from S red to M green.

Mixing for and while

Any loop can go inside any other loop. Here a while loop keeps a menu running and a for loop prints the options:

pythonpython
options = ["start", "settings", "quit"]
 
while True:
    for number, option in enumerate(options, start=1):
        print(number, option)
    choice = input("Choose: ")
    if choice == "3":
        break

Break out of nested loops

break leaves only the innermost loop that contains it. The outer loop keeps going:

pythonpython
for row in range(3):
    for col in range(3):
        if col == 1:
            break
        print(row, col)

This prints 0 0, 1 0, and 2 0.

To stop both loops at once, the cleanest way is to put them in a function and return:

pythonpython
def find(grid, target):
    for r, row in enumerate(grid):
        for c, value in enumerate(row):
            if value == target:
                return r, c
    return None
 
 
grid = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(find(grid, 5))  # (1, 1)

return ends the whole function, so both loops stop. The other option is a flag variable that the outer loop checks after the inner loop ends. The details of break are in break, continue, and pass.

Nested loops and speed

The work multiplies. Two nested loops over 1,000 items each run the inner block 1,000,000 times. Three levels over 1,000 items would be a billion.

Before nesting a loop over a large collection, ask whether a dictionary or set lookup could replace the inner loop. Checking if x in some_set is close to instant, however large the set is.

pythonpython
orders = ["u1", "u3", "u1", "u7"]
active_users = {"u1", "u2", "u3"}   # a set
 
for user in orders:
    if user in active_users:        # no inner loop needed
        print(user, "is active")

Common mistakes

MistakeWhat happensFix
Same variable name in both loopsThe inner loop overwrites the outer valueUse different names, such as row and col
A line indented at the wrong levelIt runs too often or too rarelyLine it up with the loop it belongs to
Expecting break to stop both loopsOnly the inner loop stopsUse a function with return, or a flag
Nesting three or four levels deepCode that is slow and hard to readMove the inner loops into a function
Rune AI

Rune AI

Key Insights

  • A nested loop is a loop inside another loop; the inner loop runs fully for every pass of the outer loop.
  • The inner block runs outer passes multiplied by inner passes.
  • Indentation decides which loop a line belongs to.
  • Nested loops suit grids, tables, nested lists, and combinations of two collections.
  • break exits only the innermost loop; use a function with return to leave both.
  • For large data, replace an inner loop with a set or dictionary lookup.
RunePowered by Rune AI

Frequently Asked Questions

What is a nested loop in Python?

A nested loop is a loop placed inside the body of another loop. For each pass of the outer loop, the inner loop runs completely, so the inner block runs outer passes multiplied by inner passes.

How do I break out of two loops in Python?

break only exits the innermost loop. To exit both, put the loops in a function and use return, or set a flag variable inside the inner loop and check it in the outer loop to break again.

Can I put a while loop inside a for loop?

Yes. Any kind of loop can be nested inside any other: for inside for, while inside for, for inside while, or while inside while.

Are nested loops slow in Python?

They can be, because the work multiplies. Two nested loops over n items do n times n steps. For small data this is fine. For large data, replace the inner loop with a set or dictionary lookup where possible.

How many levels of nested loops can Python have?

Python does not set a small limit, but more than two or three levels is hard to read. Move the inner loops into a function with a clear name when the nesting gets deep.

Conclusion

Nested loops handle anything with two dimensions: rows and columns, lists inside lists, or every pairing of two collections. Read them like a clock, keep them to two levels where you can, and remember that the work multiplies with each level.