Placement Prep

Nested Loops in Python: Types, Syntax, and Examples

Four types of nested loops in Python with working code and placement-round examples. Covers for, while, mixed variants, and break/continue control.

By FACE Prep Team 6 min read
python nested-loops placement-prep loops coding-practice python-basics for-loop

A nested loop in Python places one loop inside another, letting the inner loop complete all its iterations for every single step of the outer loop.

What a nested loop does

The outer loop drives progress through a sequence. The inner loop resets completely at the start of each outer step and runs through its entire sequence before the outer loop advances again.

A concrete count: if the outer loop runs 3 times and the inner loop runs 4 times per outer step, the total number of iterations is 3 × 4 = 12. That arithmetic is the key to reading nested loops and to estimating how long they take on large inputs.

The Python documentation on for statements shows the base syntax. Nested loops extend that syntax by placing one complete loop inside the body of another:

for outer_var in outer_sequence:
    for inner_var in inner_sequence:
        # executes len(outer_sequence) × len(inner_sequence) times total
        statement(s)

Four loop-type combinations exist in Python:

  • for loop inside for loop
  • while loop inside while loop
  • for loop inside while loop
  • while loop inside for loop

All four behave identically at the structural level: the inner loop completes before the outer loop advances. Placement questions favour the for-in-for combination because the iteration bounds are explicit in the range() arguments, making it straightforward to trace on paper.

Nested for loop in Python

The for-in-for pattern is the most common variant in campus placement coding rounds. Both loops use range() to define their bounds, and the only line that changes across most placement variations is the inner loop’s range expression.

Multiplication table example

for i in range(1, 4):
    for j in range(1, 11):
        print(f"{i} x {j} = {i * j}")
    print()
  • Outer loop: i takes values 1, 2, 3 (3 iterations)
  • Inner loop: j takes values 1 through 10 (10 iterations per outer step)
  • Total iterations: 3 × 10 = 30
  • The print() after the inner loop adds a blank line between tables

Sample output for i = 2:

2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
2 x 4 = 8
2 x 5 = 10
2 x 6 = 12
2 x 7 = 14
2 x 8 = 16
2 x 9 = 18
2 x 10 = 20

Triangular number pattern

Pattern printing is a placement staple. The key insight: the inner loop’s upper bound is the current value of the outer loop variable.

rows = 4
for i in range(1, rows + 1):
    for j in range(1, i + 1):
        print(j, end=" ")
    print()

Output:

1 
1 2 
1 2 3 
1 2 3 4 

The inner loop runs i times on row i. Row 1 runs the inner loop once, row 4 runs it four times. This expanding inner bound is the mechanism behind every triangular pattern. Off-by-one errors in the range() arguments are the most frequent source of wrong output in timed tests. Always check whether the bound should be i or i + 1.

Nested while loop and mixed combinations

Nested while loop

a = 1
while a <= 3:
    b = 1
    while b <= 3:
        print(b, end=" ")
        b += 1
    print()
    a += 1

Output:

1 2 3 
1 2 3 
1 2 3 

The b = 1 reset at the top of each outer iteration is the critical line. Without it, b ends at 4 after the first inner run and the inner while condition fails immediately on every subsequent outer step, producing only one row instead of three. Forgetting to reset the inner counter is the most common bug in nested while loops.

for loop inside while loop

data = [40, "Python"]
count = len(data)
i = 0
while i < count:
    for item in data:
        print(item)
    i += 1

Output:

40
Python
40
Python

The while loop runs twice (for i = 0 and i = 1). Each outer iteration triggers the inner for loop, which prints all items in data. The total prints are 2 × 2 = 4 lines.

while loop inside for loop

data = [40, "Python"]
count = len(data)
for item in data:
    index = 0
    while index < count:
        print(data[index])
        index += 1

Output is identical: 40, Python, 40, Python. Both mixed variants produce the same result here because both outer sequences have the same length. The structural principle holds for any lengths: inner completes fully before outer advances.

Controlling nested loops: break and continue

The Python docs on break and continue note that both statements apply to the innermost loop they appear in. In nested loops, this scope distinction matters.

break in a nested loop

items = [40, "Python", 0, 30.45]
for item in items:
    if item == 0:
        break
    print(item)

Output:

40
Python

The loop stops at 0 and never reaches 30.45. In a nested loop, the same break would stop only the inner loop and return control to the outer loop, which would continue with its next iteration.

continue in a nested loop

items = [40, "Python", 0, 30.45]
for item in items:
    if item == 0:
        continue
    print(item)

Output:

40
Python
30.45

continue skips the iteration where item == 0 and moves to the next value. The 30.45 prints because the loop carries on after the skip.

Exiting both loops at once

Python has no multi-level break keyword. The idiomatic approach uses a flag variable:

stop = False
for i in range(5):
    for j in range(5):
        if i == 2 and j == 2:
            stop = True
            break
    if stop:
        break

The inner break exits the inner loop. The outer loop then checks stop and breaks itself. Some teams use an exception for this instead, but the flag pattern is the most readable and appears most often in placement-round model answers.

Nested loops in 2D array traversal

A 2D list (matrix) in Python is a list of lists. Nested loops are the direct way to visit every element: the outer loop iterates rows, the inner loop iterates columns.

matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

total = 0
for row in matrix:
    for element in row:
        total += element

print("Sum:", total)

Output: Sum: 45 (the integers 1 through 9 sum to 45).

This traversal pattern links directly to array sum problems, matrix multiplication questions, and grid-search problems in placement tests. The index-based version is equally valid and required when the question asks to modify the matrix in place:

for i in range(len(matrix)):
    for j in range(len(matrix[0])):
        print(matrix[i][j], end=" ")
    print()

Both styles appear in campus tests. The element-based loop reads more clearly; the index-based loop is needed when the position (i, j) matters, for example when checking neighbours or swapping values.

Time complexity of nested loops

When the outer loop runs n times and the inner loop runs n times per outer step, the total iterations are n × n = n². This is the O(n²) time complexity that placement interviewers ask about.

The O(n²) result holds only when both loop bounds grow with the same variable. If the inner loop always runs a fixed number of times regardless of n, the complexity is different. In the multiplication table example above, the outer loop runs n times and the inner loop always runs 10 times. Total iterations are 10n, which simplifies to O(n), not O(n²).

Recognising this distinction matters in placement technical interviews at product companies. Being able to say “this specific nested loop is O(n) because the inner loop runs a constant 10 iterations, not O(n²)” shows that you understand the code rather than just pattern-matching on “nested loop equals O(n²).”

For the triangular pattern earlier, the outer loop runs n times and the inner loop runs 1, 2, 3, … , n times. Total iterations are 1 + 2 + 3 + … + n = n(n+1)/2, which simplifies to O(n²). Pattern-printing questions, matrix traversal, and brute-force search problems all follow this same analysis.

Getting comfortable with nested loops at the level of the Python practice programs here is the baseline before stepping up to 2D dynamic programming or graph traversal in later placement rounds.

Pattern printing in placement tests checks whether your nested loops produce the right shape under time pressure. Once that control is solid, the next level is applying the same loop logic to real structured data. TinkerLLM runs Python-based exercises on text streams and API responses, applying the same loop-driven iteration to inputs that are not toy lists. The entry point is ₹299.

Primary sources

Frequently asked questions

What is a nested loop in Python?

A nested loop is a loop placed inside another loop. The inner loop completes all its iterations for every single step of the outer loop. This applies to for loops, while loops, and any combination of the two.

How do I break out of both loops at once in Python?

Python's break statement exits only the loop it appears in. To stop both loops, use a flag variable: set the flag inside the inner break, check it in the outer loop condition, and break again if the flag is set.

What is the time complexity of a nested loop?

If the outer loop runs n times and the inner loop also runs n times per outer step, total iterations are n times n, giving O(n²). This quadratic growth is why placement interviewers ask about loop nesting when reviewing code for efficiency.

When do nested loops appear in placement coding rounds?

Pattern printing questions (half-pyramid, number triangle, diamond) almost always require nested loops. 2D array traversal and matrix operations also use nested loops. These appear in TCS NQT, Infosys InfyTQ, and similar campus rounds.

Can I mix for and while loops in Python?

Yes. Python allows a for loop inside a while loop or a while loop inside a for loop. The execution logic is identical: the inner loop completes all its iterations for every single step of the outer loop, regardless of the loop type.

What does continue do inside a nested loop?

The continue statement skips the rest of the current iteration in the loop it appears in. Inside a nested loop, a continue in the inner loop skips to the next inner iteration only. The outer loop is unaffected.

Build AI projects

A self-paced playground for building with LLMs.

TinkerLLM is FACE Prep's sister property. A guided environment for shipping real LLM applications, the kind of project that earns a paragraph on your resume, not a line.

Try TinkerLLM (₹299 launch)
Free AI Roadmap PDF