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.
for row in range(1, 4):
for col in range(1, 3):
print(row, col)1 1
1 2
2 1
2 2
3 1
3 2The 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:
- The outer loop sets
rowto 1. - The inner loop runs completely:
colis 1, then 2. - The inner loop ends, and control returns to the outer loop.
- The outer loop sets
rowto 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
for a in range(1, 4):
for b in range(1, 4):
print(a * b, end="\t")
print()1 2 3
2 4 6
3 6 9end="\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:
for row in range(1, 5):
for _ in range(row):
print("*", end="")
print()*
**
***
****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:
grid = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
]
total = 0
for row in grid:
for value in row:
total += value
print(total) # 45The 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
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:
options = ["start", "settings", "quit"]
while True:
for number, option in enumerate(options, start=1):
print(number, option)
choice = input("Choose: ")
if choice == "3":
breakBreak out of nested loops
break leaves only the innermost loop that contains it. The outer loop keeps going:
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:
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.
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
| Mistake | What happens | Fix |
|---|---|---|
| Same variable name in both loops | The inner loop overwrites the outer value | Use different names, such as row and col |
| A line indented at the wrong level | It runs too often or too rarely | Line it up with the loop it belongs to |
Expecting break to stop both loops | Only the inner loop stops | Use a function with return, or a flag |
| Nesting three or four levels deep | Code that is slow and hard to read | Move the inner loops into a function |
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.
Frequently Asked Questions
What is a nested loop in Python?
How do I break out of two loops in Python?
Can I put a while loop inside a for loop?
Are nested loops slow in Python?
How many levels of nested loops can Python have?
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.
More in this topic
Python break, continue, and pass Explained
break exits a loop, continue skips to the next pass, and pass does nothing at all. See how each one works in for and while loops, and when to use them.
Python while Loops Explained
A while loop repeats a block for as long as a condition stays true. Learn the syntax, the while True pattern, how to validate input, and how to avoid infinite loops.
Common Python Mistakes Beginners Make
Twelve mistakes nearly every Python beginner makes, with the exact error message each one produces and the fix. Learn to recognise them and you will debug much faster.