PythonConditional Statements and LoopsPython nested loops

What is a nested loop?

Question 57 of 88 · Updated

On this page

A nested loop is a loop placed inside the body of another loop. The enclosing loop is commonly called the outer loop, and the enclosed loop is called the inner loop. Whenever execution reaches the inner loop during an outer iteration, Python executes that inner loop according to its own iteration or termination rule.

Nested loops are useful when processing two-dimensional data, visiting combinations of values, traversing groups of records or repeating an operation whose input depends on another iteration. They can combine for and while statements, and more than two nesting levels are possible.

1. Basic syntax and execution order#

PYTHON
for row in range(2): for col in range(3): print(row,col)

Output:

0 0
0 1
0 2
1 0
1 1
1 2

The outer loop supplies row values 0 and 1. For each row, the inner loop supplies column values 0, 1 and 2. The outer loop does not advance to the next row until the inner loop finishes, unless another control transfer changes execution.

Outer iterationInner iterationsPrinted coordinates
row = 03(0, 0), (0, 1), (0, 2)
row = 13(1, 0), (1, 1), (1, 2)
Total6All six ordered pairs

Indentation determines which statements belong to each loop. Code at the inner body's indentation repeats for each column; code in the outer body after the inner loop executes once per outer iteration that reaches it.

Loading diagram…

This flowchart illustrates ordinary completion of the two for loops. It omits early exits, exceptions and optional else suites.

2. Independent versus dependent inner loops#

In the rectangular example, every row uses the same three-column range. The inner loop's iteration count is independent of the outer value.

A dependent inner loop uses the outer value to determine its own bounds or input. For example, in a collection of groups, each outer iteration can provide a group of a different size. Even though the source code has two levels of loops, the actual number of inner iterations depends on the data.

PYTHON
for row in [[2,4],[],[6]]: print(sum(row))

Output:

6
0
6

The outer loop traverses three rows. The sum function consumes the values of each row, including the empty row, whose sum is zero. There are three actual numeric values to aggregate, not nine. Although the inner traversal is expressed using a built-in function here, the amount of data processed still depends on the row lengths.

This distinction matters when estimating runtime. Count the actual inner work for each outer iteration rather than automatically multiplying two assumed dimensions.

3. Triangular iteration: visit each unordered pair once#

PYTHON
pairs=[] for i in range(4): for j in range(i+1,4): pairs.append((i,j)) print(pairs)

Output:

[(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)]

The inner loop starts at i + 1. Therefore, it visits only pairs with j greater than i. It excludes self-pairs such as (1, 1) and reversed duplicates such as (2, 0).

ij valuesInner iterations
01, 2, 33
12, 32
231
3None0

For n items, the number of visited index pairs is n(n - 1)/2.

Loading diagram…

This is still quadratic in n when all pairs must be visited. Reducing the number of pairs from n squared to roughly half that amount improves the constant factor, not the asymptotic growth rate.

The example generates index pairs. If two input values are equal but occur at different indexes, those are still distinct index positions. Whether such pairs are considered duplicates depends on the application's requirements.

4. Combining for and while loops#

PYTHON
for row in range(2): col=0 while col<3: print(row,col) col+=1

Output:

0 0
0 1
0 2
1 0
1 1
1 2

The outer for loop supplies row indexes. The inner while loop advances a column counter until it reaches three.

The placement of col = 0 is important. It resets the inner counter at the start of each outer iteration. If col were initialized only before the outer loop, it would remain three after the first inner traversal. The second outer iteration would then skip the inner body entirely.

When the repetition count is known and the desired indexes form a range, two for loops are generally simpler. A while loop is useful when the inner repetition depends on changing state or another condition rather than a straightforward iterable.

5. Inner iterators must be reusable or recreated#

PYTHON
cols=iter([1,2]) print([(r,c) for r in ['A','B'] for c in cols]) cols=[1,2] print([(r,c) for r in ['A','B'] for c in cols])

Output:

[('A', 1), ('A', 2)]
[('A', 1), ('A', 2), ('B', 1), ('B', 2)]

In the first expression, cols is a single iterator. It is exhausted while processing the first outer value. The second outer value does not receive any columns.

In the second expression, cols is a reusable list. Each inner traversal obtains a new iterator, so both outer values are paired with both columns.

A nested comprehension with two for clauses follows the corresponding nested-loop traversal order: the leftmost for is the outer iteration.

Loading diagram…

This is particularly important for file streams, database cursors and generators. Do not assume that an iterable can always be restarted. When the inner data must be reused, choose a reusable representation, explicitly recreate the iterator when possible, or redesign the traversal. Materialization has a memory cost and is inappropriate for an unbounded source.

6. Practical example: independent rows in a grid#

PYTHON
grid=[[0]*3 for _ in range(2)] grid[0][1]=9 print(grid)

Output:

[[0, 9, 0], [0, 0, 0]]

The outer comprehension creates a separate list for each row. The inner list expression creates three initial integer entries. Updating the first row's second position leaves the second row unchanged.

Avoid constructing mutable rows with an expression such as [[0] * 3] * 2. Repeating the outer list copies references to the same inner list, not independent row objects. Modifying one row can unexpectedly appear to modify the other.

The earlier mutability lesson explains object aliasing in detail. Here the key design rule is that a grid requiring independently mutable rows must construct those rows independently.

7. Practical example: calculate per-row totals#

PYTHON
def totals(rows): result=[] for row in rows: total=0 for value in row: total+=value result.append(total) return result print(totals([[1,2],[],[3,4,5]]),totals([]))

Output:

[3, 0, 12] []

The outer loop visits each row. The inner loop accumulates the values of that particular row. Initializing total inside the outer loop but before the inner loop is essential: each row must begin with a fresh accumulator.

An empty row produces zero. An empty outer collection produces an empty result. These are explicit and useful boundary behaviors.

For simple summation, a comprehension using sum(row) is a more compact alternative. The explicit nested-loop form makes the accumulator lifetime visible and can be extended when per-value validation or other processing is needed.

Let R denote the number of rows and N the total number of values across all rows. Under bounded-cost retrieval and arithmetic assumptions, this implementation requires O(R + N) time and O(R) output storage. It uses a constant number of additional working variables, excluding the output and any input-provided iterator state.

The example assumes numeric values with compatible addition semantics. Production financial calculations additionally require validated units, precision and rounding policies.

8. Cartesian products with itertools.product#

PYTHON
from itertools import product print(list(product(['S','M'],['red','blue'])))

Output:

[('S', 'red'), ('S', 'blue'), ('M', 'red'), ('M', 'blue')]

The product function represents the Cartesian product of its inputs. Each size is paired with each color, in the same order as ordinary nested loops over the two lists.

For finite independent collections, itertools.product can make the combinatorial intention clearer. It produces output tuples through an iterator, but it first consumes its input iterables into reusable pools. It is not suitable for an infinite input iterable. Input pool storage is proportional to the sizes of those pools, and collecting all output tuples can require much more memory.

Use ordinary nested loops when the inner iterable depends on the outer item, when separate per-level actions are important, or when explicit nested control flow is easier to understand.

9. Stream coordinates from irregular rows#

PYTHON
def coordinates(rows): for r,row in enumerate(rows): for c,value in enumerate(row): yield r,c,value print(list(coordinates([[5],[],[7,8]])))

Output:

[(0, 0, 5), (2, 0, 7), (2, 1, 8)]

The generator visits every available element and supplies its row index, column index and value. Because the column enumeration is initialized for each row, each row's first value has column index zero. The empty row contributes no coordinate, but the subsequent row still has index two.

The generator can yield coordinates incrementally rather than building an entire coordinate list inside the function. The list conversion in this small example is only for display. A caller processing a large input can consume the results one at a time.

Under ordinary bounded-cost iteration assumptions, traversing all coordinates requires O(R + N) time. The generator keeps a bounded amount of traversal state relative to the number of rows and values, excluding memory retained by its input iterators or consumer. Materializing the result requires O(N) output entries.

10. Break and continue in nested loops#

The earlier break and continue lessons demonstrate that both statements target the innermost enclosing loop.

  • Break exits that loop, not automatically every enclosing loop.
  • Continue advances that loop's iteration mechanism, not automatically the outer loop.
  • Return leaves the enclosing function and can therefore exit multiple nested loops when a search helper finds its result.

If an inner search determines that the entire operation is complete, a helper function with an early return is often clearer than maintaining several interdependent flags. When the outer loop must continue under a different policy, express that policy at its own level.

The loop-else construct also has its own completion semantics. A break from an inner loop does not by itself suppress the outer loop's else suite. The next lesson examines loop else more deeply.

11. Time complexity of nested loops#

There is no single time complexity that applies to every nested loop. The correct calculation depends on iteration counts and the work performed.

StructureInner work, assuming constant-cost bodyTypical total time
R outer iterations, C inner iterations eachR*CO(R + R*C)
n outer iterations, n inner iterations eachn*nO(n²)
j starts at i+1 and stops before nn(n-1)/2O(n²)
Rows with lengths k1, k2, ..., kRSum of row lengths NO(R + N)
Fixed three inner iterations for each of n items3nO(n)

The rectangular bound includes the outer traversal overhead, which matters when the inner dimension is zero. With positive dimensions, O(R*C) is the conventional simplified bound.

A loop that exits early may perform less work in practice. Worst-case analysis must still account for inputs where the early exit is never reached or occurs at the end.

Also distinguish auxiliary space from output space. Printing each pair as it is visited can avoid storing all pairs, while appending every pair to a list requires memory proportional to the number of pairs produced. Actual operation costs can depend on operand sizes, comparison methods, I/O and the iteration protocol.

The verification suite independently compared triangular counts against n(n-1)/2 for n from 0 through 100, and rectangular counts against R*C for both dimensions from 0 through 10.

12. Common mistakes and good practices#

MistakeCorrection
Incorrect indentationIdentify which statements should execute per outer iteration and which per inner iteration
Forgetting to reset inner stateInitialize state at the start of the relevant outer iteration
Reusing an exhausted iteratorSupply a reusable iterable or recreate its iterator
Assuming rectangular dataHandle variable row lengths and empty rows
Sharing mutable grid rowsConstruct each row independently
Expecting break to exit every loopUse a helper or explicit outer-loop control
Assuming all nested loops are quadraticCount actual inner iterations and body costs

Nested loops are not inherently bad. When an operation genuinely needs to visit every pair or every cell, nested traversal may be the most straightforward correct implementation. Avoid materializing unnecessary intermediate results and keep the loop bodies understandable.

When a nested search is performing repeated work that could be indexed, cached or expressed through a more suitable algorithm, a redesign may reduce complexity. That optimization topic is covered separately in the upcoming lesson on avoiding unnecessary nested loops.

Frequently asked questions#

How many times does an inner loop run?#

It runs according to its own iteration rule each time the outer body reaches it. For R outer iterations and C inner iterations per outer iteration, the inner body executes R*C times, assuming no early exit.

Can a while loop be nested inside a for loop?#

Yes. Python permits combinations of for and while statements. Each loop follows its own control-flow rules.

Are nested loops always O(n²)?#

No. They are quadratic only under appropriate assumptions, such as n outer iterations and n constant-cost inner iterations per outer iteration. Fixed inner bounds, dependent ranges, irregular input sizes and early exits change the analysis.

What happens when the inner iterable is empty?#

The inner body executes zero times. The enclosing outer iteration can continue normally.

Can a nested loop be replaced with itertools.product?#

For independent finite iterables, product can express Cartesian traversal clearly. It is not equivalent to every nested loop, especially when the inner input depends on the outer value or when intermediate actions matter.

Interview-ready answer#

A nested loop is a loop inside another loop. The outer loop advances according to its own rule, and each outer iteration that reaches the inner loop runs that inner loop according to its input or condition. Nested loops are commonly used for grids, grouped records and combinations. Their complexity depends on the sum of the actual inner work: two independent n-item loops with constant-cost bodies are O(n²), but a fixed-size inner loop is O(n), and irregular rows require counting the total values and row overhead. Correct nested-loop design accounts for indentation, inner-state initialization, iterator reuse, early exits and output memory.

Official references#

Verification note: Nine fenced Python example groups matched their documented outputs on CPython 3.13.5. The triangular and rectangular counting formulas passed an additional 222 assertions. Three fenced Mermaid flowcharts were manually reviewed; the local Mermaid package and CLI were unavailable, so parser validation and public-site rendering were not performed. Official references are supplied under the authorized offline research exception; live documentation and the Supabase changelog were not checked.

Related questions

Explore other topics:Forward Deployed EngineeringMachine LearningSQL: Structured Query LanguageAI System Design