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:
Table of contents
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
forloop uses the range() function to iterate over the first ten numbers. - For each outer number, the inner
forloop 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.

Example: Write a nested for loop program to print a multiplication table in 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
forloop iterates over the numbers 1 to 10, so it runs 10 times. - In the first iteration of the outer loop,
iis 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:
- 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
forloop iterates over the list of names. - In each iteration of the outer loop, the inner
whileloop runs five times to print the current name five times.
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
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
Output:
1 2 3 4 5 6 7 8 9
Example 2: Calculate the sum of all values in a matrix
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.
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:
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
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.
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.
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:
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:
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:
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.
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:
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
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
whileloop iterates over the numbers up to 100. - In each iteration of the outer loop, the inner
forloop runs from 1 up to the current number and adds up its divisors to check whether the number is perfect.
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.
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
nitems, likefor i in my_list, runsntimes, so its time complexity isO(n). - A nested loop where the outer loop runs
ntimes and the inner loop runsmtimes executes the inner bodyn × mtimes, so it isO(n × m). - When both loops go over the same
nitems, that becomesO(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
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,
rowandvalue), 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
setordictinstead of an inner loop. Checkingif x in my_setis 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
forandwhileloops 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.
breakandcontinueaffect only the innermost loop. To exit all loops, use a flag, a function withreturn, or the for-else trick.- List comprehensions with multiple
forclauses 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.
