MyInternships.in

Python Control Flow

Python Nested Loops

A nested loop is simply a loop placed inside another loop, letting you repeat an action for every combination of two (or more) sequences — commonly used to work with grids and patterns.


Writing a Nested Loop

The inner loop runs completely for every single iteration of the outer loop. So if the outer loop runs 3 times and the inner loop runs 4 times, the inner block executes a total of 12 times.

Basic nested loop
Python
for i in range(1, 4):
    for j in range(1, 3):
        print(f"i={i}, j={j}")

Building Star Patterns

Nested loops are the classic way to print shapes and patterns, since the outer loop typically controls the row and the inner loop controls what gets printed in that row.

Star pattern (triangle)
Python
rows = 5
for i in range(1, rows + 1):
    print("*" * i)
Output
Output
*
**
***
****
*****

Nested Loops with a 2D List

Nested loops are also the standard way to visit every cell of a 2D structure, like a list of lists (a common way to represent a grid or matrix).

Looping over a 2D list
Python
matrix = [[1, 2, 3], [4, 5, 6]]
for row in matrix:
    for value in row:
        print(value, end=" ")
    print()

Breaking Out of Nested Loops

A plain break only exits the innermost loop it is written in — the outer loop keeps going. To stop everything, use a flag variable checked in the outer loop, or restructure the logic into a function and return early.

Using a flag to stop both loops
Python
found = False
for i in range(3):
    for j in range(3):
        if i == 1 and j == 1:
            found = True
            break
    if found:
        break
print("Stopped at", i, j)

A Note on Time Complexity

Each additional level of nesting multiplies the work: a single loop over n items is O(n), but two nested loops over n items become O(n²), since the inner loop repeats fully for every outer iteration. Watch out for deeply nested loops over large lists, as performance can drop sharply.

⚠️

Three or more levels of nesting quickly become hard to read and slow to run. If you find yourself nesting deeply, consider breaking the logic into separate functions.

💡

When printing patterns, first work out the logic with plain numbers (like i and j) before switching to characters like * — it makes debugging much easier.

Related Python Topics

Keep learning with these closely related lessons.

Ready to use your Python skills?

Find Python, data science and software internships and fresher jobs across India.

Browse Python Internships