Himanshu SharmaSoftware engineer
Let’s talk

Python Tutorial · Lesson 19 of 70

Python nested loops: loops inside loops

Put one Python loop inside another to work with grids, tables and pairs, learn how many times the inner loop runs, and how break behaves in nested loops.

12 minControl flowUpdated 14 November 2026

Awaiting technical review. This lesson is readable but not yet listed in search engines.

By the end of this lessonWrite nested loops for tables, patterns and pairs of values, predict how many times they run, and stop them correctly.

After this lesson you can put a loop inside a loop, which is how programs handle tables, grids and every combination of two things. The idea is simple, but the order in which things happen takes a moment to picture.

The idea

A nested loop is a loop whose block contains another loop. For each pass of the outer loop, the inner loop runs from start to finish:

python
for day in ["Mon", "Tue"]:
    for shift in ["morning", "evening"]:
        print(day, shift)
result
Mon morning
Mon evening
Tue morning
Tue evening

Read the output carefully. Mon stays the same while the inner loop goes through both shifts. Only then does the outer loop move to Tue and the inner loop starts again from the beginning. The inner loop is like the minute hand of a clock, and the outer loop is the hour hand.

Counting the passes

If the outer loop runs 3 times and the inner loop runs 4 times, the inner block runs 3 times 4, which is 12 times. You can check that by counting:

python
count = 0
for row in range(3):
    for column in range(4):
        count += 1
print(count)
result
12

This multiplication is worth remembering. A nest with 1,000 passes in each loop does a million passes, and a third level would do a billion. Nested loops are powerful but can become slow on large data.

Building a times table

The classic use is a table. Here is a small multiplication table, one row per outer pass:

python
for row in range(1, 4):
    for column in range(1, 4):
        print(row * column, end=" ")
    print()
result
1 2 3 
2 4 6 
3 6 9 

The inner print uses end=" " so that the numbers in one row stay on one line, separated by spaces. When the inner loop finishes, the empty print() ends the line. Notice that this last print() is indented to line up with the inner for, which means it belongs to the outer loop and runs once per row.

If you indented it by one more level, it would run after every number and the table would turn into a single column. Indentation decides which loop a line belongs to.

Drawing a pattern

Nested loops are good for patterns. This prints a right-angled triangle of stars:

python
for size in range(1, 5):
    for _ in range(size):
        print("*", end="")
    print()
result
*
**
***
****

On the first row the inner loop runs once, on the second twice, and so on. The inner loop's range depends on the outer variable, which is a common and useful trick.

All pairs

Whenever you need every combination of two things, nested loops are the tool. Imagine a small café pairing each drink with each size:

python
drinks = ["tea", "coffee"]
sizes = ["small", "large"]
for drink in drinks:
    for size in sizes:
        print(size, drink)
result
small tea
large tea
small coffee
large coffee

break in a nested loop

break only ends the loop it sits inside. Here it stops the inner loop, but the outer loop keeps going:

python
for aisle in [1, 2, 3]:
    for item in ["milk", "bread", "eggs"]:
        if item == "bread":
            break
        print("Aisle", aisle, item)
result
Aisle 1 milk
Aisle 2 milk
Aisle 3 milk

In each aisle the inner loop reaches bread and stops, so eggs is never printed, but all three aisles are still visited.

If you need to leave both loops at once, there are a few options: put the loops in a function and use return, which later lessons cover, or use a flag variable that the outer loop checks. You can also reorganise the code so that you only need a single loop.

Picturing a grid

Many nested loops are easiest to understand as a grid. Imagine a table with rows and columns, such as seats in a small cinema. The outer loop picks a row and the inner loop walks across the columns of that row. When the row ends, you move down one and start across again.

If you ever lose track, draw the grid on paper and put your finger on the cell being handled. Say aloud the values of the outer and inner variables at that moment. This is the same tracing technique you use for single loops, with one extra variable.

When the data is a list inside a list, such as the marks of several students, the same pattern applies: the outer loop visits each student and the inner loop visits that student's marks. You will see this shape again in the nested collections lesson.

Common mistakes

  • Wrong indentation. A line indented to the wrong level belongs to the wrong loop. Check which loop each line should run with.
  • Reusing the same loop variable. for i in ... inside another for i in ... overwrites i and confuses the outer loop. Use different names.
  • Forgetting the nested cost. Two loops over a large list can take a long time.
  • Expecting break to leave both loops. It leaves only the inner one.
  • Forgetting print() to end a row. Without it all the rows run together on one line.

Exercise

Print the numbers 1 to 3 in a row for each of three rows, but replace any number that equals the row number with a dash. So row 2 should look like 1 - 3.

Show one possible answer
python
for row in range(1, 4):
    for number in range(1, 4):
        if number == row:
            print("-", end=" ")
        else:
            print(number, end=" ")
    print()
result
- 2 3 
1 - 3 
1 2 - 

The test compares the inner variable with the outer one, which is only possible because the inner loop sits inside the outer loop's block.

Next: bring it all together with control flow practice.

Key points

  • A nested loop is a loop inside the block of another loop.
  • The inner loop runs completely for every single pass of the outer loop.
  • Total passes equal outer passes multiplied by inner passes, so big nests get slow.
  • break and continue only affect the innermost loop they are written in.

Check yourself

1. An outer loop runs 3 times and an inner loop runs 4 times each. How many times does the inner block run in total?
2. In nested loops, which one changes fastest?
3. What does a break in the inner loop do?
4. What does print("*", end="") do inside a loop?