PYnative

Practice Coding

  • Python â–¼
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Coding Exercises â–¼
    • Python Exercises
    • C++ Exercises
    • C Programming Exercises
    • Java Exercises
    • C# Exercises
  • MCQsâ–¼
    • Python MCQ Quizzes
    • Java MCQ Quizzes
    • C++ MCQ Quizzes
  • Compilersâ–¼
    • Online Python Compiler
    • Online C Compiler
    • Online C++ Compiler
    • Online Java Compiler
    • Online C# Compiler
Home » Python » Nested Loops in Python

Nested Loops in Python

Updated on: November 28, 2026 | 40 Comments

In Python, a loop inside another loop is called a nested loop. In this tutorial, you’ll learn how nested loops work, how to write nested for and while loops, how to control them with break and continue, and when to use them (or avoid them), with plenty of examples.

Also, Solve:

  • Python loop Exercise
  • Python loop Quiz

Table of contents

  • What is a nested loop in Python?
    • How a nested loop works
  • Python nested for loop
    • Nested loop to print a pattern
    • While loop inside a for loop
    • Practice: Print a rectangle pattern with 5 rows and 3 columns of stars
  • Iterate a nested list (2D list)
  • Break a nested loop
    • Break out of all nested loops
  • Continue a nested loop
  • Single-line nested loops using list comprehension
  • Nested while loop in Python
    • for loop inside a while loop
  • Replace nested loops with itertools.product()
  • When to use a nested loop in Python?
  • Summary

What is a nested loop in Python?

A nested loop is a loop placed inside the body of another loop. The outer loop and inner loop can be of any type, such as a while loop or a for loop. For example, an outer for loop can contain a while loop, and vice versa.

An outer loop can contain more than one inner loop, and you can nest loops as many levels deep as you need, although more than two or three levels quickly becomes hard to read.

Nested loops are typically used to work with multidimensional data, such as printing a two-dimensional table, processing a matrix, or iterating over a list that contains other lists.

Nested loops are part of Python’s control flow statements, an important topic in the basics of Python.

How a nested loop works

  • The outer loop starts its first iteration.
  • The inner loop then runs all of its iterations from start to finish.
  • Only after the inner loop is done does the outer loop move to its next iteration, and the inner loop starts over again.
  • This repeats until the outer loop is finished.

Because of this, the total number of times the inner loop body runs equals the outer loop’s iterations multiplied by the inner loop’s iterations. For example, an outer loop of 3 iterations with an inner loop of 4 iterations runs the inner body 3 × 4 = 12 times.

Python nested for loop

In Python, the for loop is used to iterate over a sequence such as a list, string, or tuple, or over other iterable objects such as range(). A nested for loop is simply a for loop inside another for loop.

Syntax of a nested for loop in Python

# outer for loop
for element in sequence:
    # inner for loop
    for element in sequence:
        body of inner for loop
    body of outer for loopCode language: Python (python)

In the following example, we use a for loop inside another for loop to print the multiplication tables of the first ten numbers.

  • The outer for loop uses the range() function to iterate over the first ten numbers.
  • For each outer number, the inner for loop runs ten times.
  • In the body of the inner loop, we print the product of the outer number and the inner number.
  • The inner loop is part of the body of the outer loop.
Python nested for loop
Python nested for loop

Example: Write a nested for loop program to print a multiplication table in Python

# outer loop
for i in range(1, 11):
    # nested loop
    # to iterate from 1 to 10
    for j in range(1, 11):
        # print multiplication
        print(i * j, end=' ')
    print()Code language: Python (python)

Output:

1 2 3 4 5 6 7 8 9 10 
2 4 6 8 10 12 14 16 18 20 
3 6 9 12 15 18 21 24 27 30 
4 8 12 16 20 24 28 32 36 40 
5 10 15 20 25 30 35 40 45 50 
6 12 18 24 30 36 42 48 54 60 
7 14 21 28 35 42 49 56 63 70 
8 16 24 32 40 48 56 64 72 80 
9 18 27 36 45 54 63 72 81 90 
10 20 30 40 50 60 70 80 90 100 
  • The outer for loop iterates over the numbers 1 to 10, so it runs 10 times.
  • In the first iteration of the outer loop, i is 1. In the next, it is 2, and so on up to 10.
  • For each iteration of the outer loop, the inner loop runs ten times, because each table goes up to ten.
  • In each iteration of the inner loop, we calculate and print the product of the two numbers. The print() after the inner loop moves to a new line, so each table appears on its own row.

Nested loop to print a pattern

Another very common use of nested loops is printing star and number patterns.

Let’s see how to use a nested loop to print the following pattern in Python.

Pattern:

*
* *
* * *
* * * *
* * * * *

Program:

rows = 5
# outer loop
for i in range(1, rows + 1):
    # inner loop
    for j in range(1, i + 1):
        print("*", end=" ")
    print('')Code language: Python (python)
  • The outer loop controls the number of rows. There are five rows, so the outer loop runs five times.
  • The inner loop controls the number of columns (stars) in each row.
  • The number of columns grows by 1 with each row: the first row has one star, the second has two, and so on.
  • In each iteration of the inner loop, we print one star.

While loop inside a for loop

It is common and useful to put one type of loop inside another. For example, you can place a while loop inside a for loop.

Suppose we want to print each name from a list five times.

  • The outer for loop iterates over the list of names.
  • In each iteration of the outer loop, the inner while loop runs five times to print the current name five times.
names = ['Kelly', 'Jessa', 'Emma']
# outer loop
for name in names:
    # inner while loop
    count = 0
    while count < 5:
        print(name, end=' ')
        # increment counter
        count = count + 1
    print()Code language: Python (python)

Output:

Kelly Kelly Kelly Kelly Kelly 
Jessa Jessa Jessa Jessa Jessa 
Emma Emma Emma Emma Emma 

Notice that count is reset to 0 inside the outer loop. Without that reset, the inner loop would run only for the first name.

Practice: Print a rectangle pattern with 5 rows and 3 columns of stars

Solve the following Python nested loop exercise.

Print the following rectangle of stars:

***
***
***
***
***

Solve more loop exercises.

Show Solution
# 5 rows
for i in range(5):
    # 3 columns
    for j in range(3):
        print('*', end='')
    print()Code language: Python (python)

Iterate a nested list (2D list)

A nested list, also called a 2D list or matrix, is a list whose items are themselves lists. The outer loop visits each row (inner list), and the inner loop visits each value in that row.

Example 1: Print a matrix row by row

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

for row in matrix:
    for value in row:
        print(value, end=' ')
    print()Code language: Python (python)

Output:

1 2 3 
4 5 6 
7 8 9 

Example 2: Calculate the sum of all values in a matrix

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
total = 0
for row in matrix:
    for value in row:
        total = total + value
print("Sum:", total)Code language: Python (python)

Output:

Sum: 45

Example 3: Loop over a dictionary of lists

Nested loops also work with other data structures. Here, the outer loop goes through each student in a dictionary, and the inner loop goes through that student’s marks.

students = {"Jessa": [85, 90], "Kelly": [72, 64]}
for name, marks in students.items():
    for mark in marks:
        print(name, mark)Code language: Python (python)

Output:

Jessa 85
Jessa 90
Kelly 72
Kelly 64

Break a nested loop

The break statement is used to exit a loop early. Inside a nested loop, break exits only the innermost loop that contains it. The outer loop keeps running.

In the following example, both the outer and the inner for loop iterate over the numbers 0 to 3. When the inner number equals the outer number, we break out of the inner loop.

Example:

for i in range(4):
    for j in range(4):
        if j == i:
            break
        print(i, j)Code language: Python (python)

Output:

1 0
2 0
2 1
3 0
3 1
3 2

As you can see, no row contains the same number twice. When i is 0, the inner loop breaks immediately, so nothing is printed for it.

Break out of all nested loops

Python has no built-in way to break out of several loops at once. Here are three common techniques, each searching a matrix for the value 5.

1. Use a flag variable

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
found = False
for i, row in enumerate(matrix):
    for j, value in enumerate(row):
        if value == 5:
            print("Found 5 at row", i, "column", j)
            found = True
            break
    if found:
        breakCode language: Python (python)

Output:

Found 5 at row 1 column 1

2. Move the loops into a function and use return

A return statement exits the whole function, including every loop inside it. This is often the cleanest option.

def find(matrix, target):
    for i, row in enumerate(matrix):
        for j, value in enumerate(row):
            if value == target:
                return i, j
    return None

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(find(matrix, 8))Code language: Python (python)

Output:

(2, 1)

3. Use the for-else trick

A loop’s else block runs only if the loop was not stopped by break. If the inner loop finishes without finding the value, else: continue moves on to the next row. If it does break, the else is skipped and the outer break runs.

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for row in matrix:
    for value in row:
        if value == 5:
            break
    else:
        continue  # inner loop didn't break, go to next row
    print("Found 5 in row", row)
    break  # inner loop broke, so break the outer loop tooCode language: Python (python)

Output:

Found 5 in row [4, 5, 6]

Continue a nested loop

The continue statement skips the current iteration and moves to the next one. When Python reaches continue, it skips all the statements below it in the loop body and jumps straight to the next iteration. In a nested loop, it affects only the innermost loop.

In the following example, the outer for loop iterates over the first list, and the inner loop iterates over the second list.

If the outer number and the inner number are the same, we skip to the next iteration of the inner loop.

Example:

first = [2, 4, 6]
second = [2, 4, 6]
for i in first:
    for j in second:
        if i == j:
            continue
        print(i, '*', j, '=', i * j)Code language: Python (python)

Output:

2 * 4 = 8
2 * 6 = 12
4 * 2 = 8
4 * 6 = 24
6 * 2 = 12
6 * 4 = 24

As you can see in the output, no number is multiplied by itself.

Single-line nested loops using list comprehension

Suppose you have two lists and want to add every number in the first list to every number in the second list. With regular loops, you need two nested loops:

first = [2, 3, 4]
second = [20, 30, 40]
final = []
for i in first:
    for j in second:
        final.append(i + j)
print(final)Code language: Python (python)

Output:

[22, 32, 42, 23, 33, 43, 24, 34, 44]

You can write the same logic more compactly, and usually a little faster, using a list comprehension with two for clauses:

first = [2, 3, 4]
second = [20, 30, 40]
final = [i + j for i in first for j in second]
print(final)Code language: Python (python)

How to write it:

  • First, write the outer loop that iterates over the first list: for i in first
  • Next, write the inner loop right after it: for i in first for j in second. The clauses appear in the same order as in the regular nested loop.
  • Then, put the expression to calculate at the front: [i + j for i in first for j in second]
  • Finally, store the result in a new list: final = [i + j for i in first for j in second]

Let’s see another example. Here we use two for clauses to build a list of pairs, and an if condition to leave out pairs where both numbers are the same.

final = [[x, y] for x in [10, 20, 30] for y in [30, 10, 50] if x != y]
print(final)Code language: Python (python)

Output:

[[10, 30], [10, 50], [20, 30], [20, 10], [20, 50], [30, 10], [30, 50]]

Nested comprehensions are also handy for flattening and transposing a matrix:

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

# flatten: one list with all values
flat = [value for row in matrix for value in row]
print(flat)

# transpose: rows become columns
transposed = [[row[c] for row in matrix] for c in range(3)]
print(transposed)Code language: Python (python)

Output:

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

Tip: Keep comprehensions short. If a nested comprehension becomes hard to read, use regular loops instead.

Nested while loop in Python

The while loop repeatedly executes a block of code as long as a condition is true. We use a while loop when the number of iterations is not fixed.

In this section, you’ll see how to use a while loop inside another while loop.

The syntax of a nested while loop in Python is as follows:

while expression:
    while expression:
        statement(s)
    statement(s)Code language: Python (python)

Example: Print the numbers 1 to 5 on a line, three times

i = 1
while i <= 3:
    j = 1
    while j <= 5:
        print(j, end=' ')
        j = j + 1
    i = i + 1
    print()Code language: Python (python)

Output:

1 2 3 4 5 
1 2 3 4 5 
1 2 3 4 5 

With nested while loops, remember to reset the inner counter (j = 1) at the start of every outer iteration, and to update both counters. Otherwise, you may get an infinite loop or an inner loop that runs only once.

for loop inside a while loop

You can also put a for loop inside a while loop.

Suppose we want to print all perfect numbers from 1 to 100. A perfect number equals the sum of its divisors, excluding itself. For example, 6 = 1 + 2 + 3.

  • The outer while loop iterates over the numbers up to 100.
  • In each iteration of the outer loop, the inner for loop runs from 1 up to the current number and adds up its divisors to check whether the number is perfect.
print('Show perfect numbers from 1 to 100')
n = 2
# outer while loop
while n <= 100:
    x_sum = 0
    # inner for loop
    for i in range(1, n):
        if n % i == 0:
            x_sum += i
    if x_sum == n:
        print('Perfect number:', n)
    n += 1Code language: Python (python)

Output:

Show perfect numbers from 1 to 100
Perfect number: 6
Perfect number: 28

Replace nested loops with itertools.product()

When you only need every combination of items from two or more lists, the product() function from Python’s built-in itertools module can replace nested loops with a single, flat loop.

from itertools import product

colors = ["red", "blue"]
sizes = ["S", "M"]

# same as: for color in colors: for size in sizes:
for color, size in product(colors, sizes):
    print(color, size)Code language: Python (python)

Output:

red S
red M
blue S
blue M

This keeps the code flat and readable, especially when you would otherwise need three or more levels of nesting.

When to use a nested loop in Python?

  • When you work with nested data, such as a list of lists, a matrix, or a dictionary of lists.
  • When you print star and number patterns made of rows and columns.
  • When you need to compare every item with every other item, for example, to find all pairs or duplicates.

Keep the time complexity in mind. The time complexity of a loop depends on how many times its body runs.

  • A single loop over n items, like for i in my_list, runs n times, so its time complexity is O(n).
  • A nested loop where the outer loop runs n times and the inner loop runs m times executes the inner body n × m times, so it is O(n × m).
  • When both loops go over the same n items, that becomes O(n²). For 1,000 items, that’s 1,000,000 iterations, so nested loops can get slow on large data.

Example: Count the iterations of a nested loop

numbers = [[1, 2, 3], [4, 5, 6]]

cnt = 0
for i in numbers:
    for j in i:
        print('iteration', cnt, end=': ')
        print(j)
        cnt = cnt + 1Code language: Python (python)

Output:

iteration 0: 1
iteration 1: 2
iteration 2: 3
iteration 3: 4
iteration 4: 5
iteration 5: 6

The outer list has 2 rows and each row has 3 values, so the inner body runs 2 × 3 = 6 times.

If a condition in the inner loop stops it early (for example, with break), fewer iterations run, and the loop finishes faster.

Tips for writing better nested loops:

  • Use different, meaningful variable names for each loop (for example, row and value), so the inner loop doesn’t overwrite the outer loop’s variable.
  • Avoid nesting more than two or three levels deep. Move inner loops into a function, or use itertools.product().
  • For lookups, consider a set or dict instead of an inner loop. Checking if x in my_set is much faster than looping through a list.
  • Use a nested loop when there is no simpler alternative. Efficient, readable code is better than clever, complex code.

Summary

  • A nested loop is a loop inside another loop. Any combination of for and while loops can be nested.
  • For each iteration of the outer loop, the inner loop runs all of its iterations.
  • The total iterations equal outer iterations × inner iterations.
  • break and continue affect only the innermost loop. To exit all loops, use a flag, a function with return, or the for-else trick.
  • List comprehensions with multiple for clauses can replace simple nested loops in one line.
  • itertools.product() gives you all combinations without writing nested loops.
  • Nested loops can be slow on large data, so keep time complexity in mind.

Ready to practice? Try the Python loop exercises, the Python loop quiz, and the pattern programs.

Filed Under: Python, Python Basics

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

I’m Vishal Hule, the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on Twitter.

Related Tutorial Topics:

Python Python Basics

All Coding Exercises:

C Exercises
C++ Exercises
Python Exercises
Java Exercises
C# Exercises

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 25+ questions
  • Each Quiz contains 25 MCQ
Exercises
Quizzes
In: Python Python Basics
TweetF  sharein  shareP  Pin

  Python Tutorials

  • Get Started with Python
  • Python Statements
  • Python Comments
  • Python Keywords
  • Python Variables
  • Python Operators
  • Python Data Types
  • Python Casting
  • Python Control Flow statements
  • Python For Loop
  • Python While Loop
  • Python Break and Continue
  • Python Nested Loops
  • Python Input and Output
  • Python range function
  • Check user input is String or Number
  • Accept List as a input from user
  • Python Numbers
  • Python Lists
  • Python Tuples
  • Python Sets
  • Python Dictionaries
  • Python Functions
  • Python Modules
  • Python isinstance()
  • Python OOP
  • Python Inheritance
  • Python Exceptions
  • Python Exercise for Beginners
  • Python Quiz for Beginners

 Explore Python

  • Python Tutorials
  • Python Exercises
  • Python Quizzes
  • Python Interview Q&A
  • Python Programs

All Python Topics

  • Python Basics
  • Python Exercises
  • Python Quizzes
  • Python File Handling
  • Python Date and Time
  • Python OOP
  • Python Random
  • Python Regex
  • Python Pandas
  • Python Databases
  • Python MySQL
  • Python PostgreSQL
  • Python SQLite
  • Python JSON

About PYnative

PYnative.com is a platform built to help developers learn by doing. Solve coding exercises, take MCQs, and run code directly in built-in online compilers.

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Coding Exercises

  • C Exercises
  • C++ Exercises
  • Python Exercises
  • Java Exercises
  • C# Exercises

MCQ Quizzes

  • Python MCQs
  • Java MCQs
  • C++ MCQs

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our:

  • Terms Of Use
  • Privacy Policy
  • Cookie Policy

Copyright © 2018–2026 pynative.com