A nested for loop is a for loop placed inside the body of another for loop. The inner loop runs from start to finish on every single iteration of the outer loop, so the inner body executes (outer count x inner count) times.
The classic example is a multiplication table, shown here in Python. The outer loop picks the row and the inner loop walks across the columns:
for row in range(1, 4):
for col in range(1, 4):
print(row * col, end=" ")
print()
Example output:
1 2 3
2 4 6
3 6 9
The same structure works in every language that has a for loop. Only the syntax around it changes.
How a nested for loop executes, step by step
Take the table above. Python evaluates it in this order:
- The outer loop sets
rowto 1. - The inner loop runs completely:
colis 1, 2, then 3, and each pass printsrow * col. That prints1 2 3. - The inner loop is exhausted, so control returns to the outer loop. The bare
print()after it ends the line. - The outer loop sets
rowto 2, and the inner loop starts again fromcol = 1. The inner loop's variable and counter are reset every time. - This repeats until the outer loop is exhausted.
That is 3 outer iterations with 3 inner iterations each, so the print(row * col, ...) line runs 9 times. The print() that ends each line sits in the outer loop's body, after the inner loop, so it runs only 3 times. Where you put a statement decides how often it runs, which is the most common source of mistakes with nesting (see below).
Python's range(1, 4) produces 1, 2 and 3. The Python tutorial states that "the given end point is never part of the generated sequence", so the last value is 3, not 4.
Nested for loop syntax in Python, Java and JavaScript
Python uses indentation for the body:
for i in range(2):
for j in range(3):
print(i, j)
Java and JavaScript use braces and a three-part header. Here is a Java loop that prints every element of a 2D array:
int[][] grid = { {1, 2, 3}, {4, 5, 6} };
for (int row = 0; row < grid.length; row++) {
for (int col = 0; col < grid[row].length; col++) {
System.out.println(grid[row][col]);
}
}
The outer loop counts rows with grid.length. The inner loop counts the columns of the current row with grid[row].length. Using the row's own length keeps the code correct when rows have different sizes.
The JavaScript version is nearly identical. This one adds up all the numbers in a grid:
const grid = [[1, 2, 3], [4, 5, 6]];
let total = 0;
for (let row = 0; row < grid.length; row++) {
for (let col = 0; col < grid[row].length; col++) {
total += grid[row][col];
}
}
console.log(total); // 21
For the single-loop syntax each language builds on, see For Loop in Java and JavaScript For Loop.
When the inner loop depends on the outer variable
The inner range does not have to be fixed. Make it depend on the outer variable and you get a triangle:
for row in range(1, 5):
for _ in range(row):
print("*", end="")
print()
Example output:
*
**
***
****
Now the inner loop runs 1, 2, 3 and 4 times. The total is 1 + 2 + 3 + 4 = 10 inner iterations, not 4 x 4 = 16. When you estimate how much work a nested loop does, add up the inner counts rather than multiplying blindly.
The same pattern appears when comparing every pair in a list. Starting the inner loop after the outer index avoids comparing an item with itself and avoids checking each pair twice:
names = ["ana", "bo", "cy"]
for i in range(len(names)):
for j in range(i + 1, len(names)):
print(names[i], names[j])
Example output:
ana bo
ana cy
bo cy
How break and continue behave in nested loops
This is where nested loops surprise people. The Python tutorial says: "The break statement breaks out of the innermost enclosing for or while loop." Its own example finds factors of composite numbers:
for n in range(2, 10):
for x in range(2, n):
if n % x == 0:
print(f"{n} equals {x} * {n//x}")
break
The break stops only the inner loop over x. The outer loop then moves on to the next n. The tutorial shows the output as 4 equals 2 * 2, 6 equals 2 * 3, 8 equals 2 * 4 and 9 equals 3 * 3.
Java and JavaScript follow the same rule. Oracle's tutorial: "An unlabeled break statement terminates the innermost switch, for, while, or do-while statement, but a labeled break terminates an outer statement." continue works the same way: it skips to the next iteration of the innermost loop only.
How to break out of both loops
You have three options, depending on the language.
A labeled break (Java and JavaScript). Put a label before the outer loop and name it in the break. This is adapted from the Java Tutorials, which search a 2D array for the value 12 and report Found 12 at 1, 0:
search:
for (i = 0; i < arrayOfInts.length; i++) {
for (j = 0; j < arrayOfInts[i].length; j++) {
if (arrayOfInts[i][j] == searchfor) {
foundIt = true;
break search;
}
}
}
MDN describes the JavaScript form the same way: break label; "breaks out of the statement labeled with label and continues executing the next statement after that."
A function with an early return (any language). Put both loops in a function and return as soon as you have the answer. Python has no labeled break, so this is the usual approach there:
def find_pair(numbers, target):
for i in range(len(numbers)):
for j in range(i + 1, len(numbers)):
if numbers[i] + numbers[j] == target:
return i, j
return None
A flag variable. Set a boolean in the inner loop and check it in the outer loop. It works everywhere but is the most clutter, so prefer the other two when you can.
How much work does a nested loop do?
Two loops over n items run the inner body n x n times. The table shows how fast that grows:
| Items (n) | Two nested loops (n x n) | Three nested loops (n x n x n) |
|---|---|---|
| 10 | 100 | 1,000 |
| 100 | 10,000 | 1,000,000 |
| 1,000 | 1,000,000 | 1,000,000,000 |
The figures are plain arithmetic, so you can check them yourself. A loop that feels instant on 100 items can crawl on 10,000. If the inner loop only looks something up, such as checking whether a value exists in a list, a set or dictionary replaces it with one lookup and leaves a single loop.
Common mistakes with nested for loops
- Reusing the same variable name. In Python,
for iinsidefor isilently overwrites the outer value on each inner pass. In Java it will not compile. Userowandcol, oriandj. - Putting a statement at the wrong level. In the multiplication table, moving
print()into the inner loop prints each number on its own line. Indentation (Python) or braces (Java, JavaScript) decide which loop owns a line. - Using the wrong bound for the inner loop. Use
grid[row].length, notgrid.length, unless the grid is square. Mixing them up gives index errors or skipped cells. - Expecting
breakto leave everything. It only leaves the innermost loop. Use one of the three options above. - Changing a list while looping over it. The Python tutorial advises that it is usually more straightforward to loop over a copy of the collection or to build a new one.
Frequently asked questions
- How many times does the inner body of a nested for loop run?
- The inner body runs once per inner iteration, for every outer iteration. If the outer loop runs 4 times and the inner loop runs 5 times each time, the inner body runs 4 x 5 = 20 times. When the inner count depends on the outer variable, add up the inner counts instead: 1 + 2 + 3 + 4 = 10.
- Does break exit all the loops in a nested for loop?
- No. An unlabeled break ends only the innermost loop that contains it, and the outer loop carries on with its next iteration. To leave several loops at once, use a labeled break in Java or JavaScript, or move the loops into a function and return from it.
- Why is a nested for loop slow on large inputs?
- The work multiplies. Two loops over n items each run the inner body n x n times, so 1,000 items means 1,000,000 iterations and 10,000 items means 100,000,000. Three levels of nesting multiply again. If the loops are searching, a set or dictionary lookup can often replace the inner loop.
- Should the inner and outer loops use different variable names?
- Yes. Use different names such as i and j, or row and col. In Python, reusing the same name makes the inner loop overwrite the outer variable. In Java, redeclaring a variable that is already in scope is a compile error.