- Nested Loops in Python
- Table of contents
- What is a Nested Loop in Python?
- Python Nested for Loop
- Nested Loop to Print Pattern
- While loop inside a for loop
- Practice: Print a rectangle Pattern with 5 rows and 3 columns of stars
- Break Nested loop
- Continue Nested loop
- Single Line Nested Loops Using List Comprehension
- Nested while Loop in Python
- for loop inside While loop
- About Vishal
- Related Tutorial Topics:
- Python Exercises and Quizzes
- Python continue Statement
- Python continue Statement Examples
- 1. continue with for loop
- 2. continue statement with the while loop
- 3. continue statement with a nested loop
- Why Python doesn’t support labeled continue statement?
Nested Loops in Python
In Python, a loop inside a loop is known as a nested loop. In this tutorial, we will learn about nested loops in Python with the help of examples.
Table of contents
What is a Nested Loop in Python?
A nested loop is a loop inside the body of the outer loop. The inner or outer loop can be any type, such as a while loop or for loop. For example, the outer for loop can contain a while loop and vice versa.
The outer loop can contain more than one inner loop. There is no limitation on the chaining of loops.
In the nested loop, the number of iterations will be equal to the number of iterations in the outer loop multiplied by the iterations in the inner loop.
In each iteration of the outer loop inner loop execute all its iteration. For each iteration of an outer loop the inner loop re-start and completes its execution before the outer loop can continue to its next iteration.
Nested loops are typically used for working with multidimensional data structures, such as printing two-dimensional arrays, iterating a list that contains a nested list.
A nested loop is a part of a control flow statement that helps you to understand the basics of Python.
Python Nested for Loop
In Python, the for loop is used to iterate over a sequence such as a list, string, tuple, other iterable objects such as range.
Syntax of using 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 loop
In this example, we are using a for loop inside a for loop. In this example, we are printing a multiplication table of the first ten numbers.
- The outer for loop uses the range() function to iterate over the first ten numbers
- The inner for loop will execute ten times for each outer number
- In the body of the inner loop, we will print the multiplication of the outer number and current number
- The inner loop is nothing but a body of an outer loop.
Example: Write a nested for loop program to print 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()
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
- In this program, the outer for loop is iterate numbers from 1 to 10. The range() return 10 numbers. So total number of iteration of the outer loop is 10.
- In the first iteration of the nested loop, the number is 1. In the next, it 2. and so on till 10.
- Next, For each iteration of the outer loop, the inner loop will execute ten times. The inner loop will also execute ten times because we are printing multiplication table up to ten.
- In each iteration of an inner loop, we calculated the multiplication of two numbers.
Nested Loop to Print Pattern
Another most common use of nested loop is to print various star and number patterns.
Let’s see how to use a nested loop to print the following pattern in Python.
rows = 5 # outer loop for i in range(1, rows + 1): # inner loop for j in range(1, i + 1): print("*", end=" ") print('')
- In this program, the outer loop is the number of rows print.
- The number of rows is five, so the outer loop will execute five times
- Next, the inner loop is the total number of columns in each row.
- For each iteration of the outer loop, the columns count gets incremented by 1
- In the first iteration of the outer loop, the column count is 1, in the next it 2. and so on.
- The inner loop iteration is equal to the count of columns.
- In each iteration of an inner loop, we print star
While loop inside a for loop
It is very common and helpful to use one type of loop inside another. we can put a while loop inside the for loop.
Assume we wanted to repeat each name from a list five times.
- Here we will iterate the list using an outer for loop
- In each iteration of outer for loop, the inner for loop execute 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()
Kelly Kelly Kelly Kelly Kelly Jessa Jessa Jessa Jessa Jessa Emma Emma Emma Emma Emma
Practice: Print a rectangle Pattern with 5 rows and 3 columns of stars
Solve the below Python nested loop exercise.
Print following rectangle of stars
# 5 rows for name in range(5): # 3 column for j in range(3): print('*', end='') print()
Break Nested loop
The break statement is used inside the loop to exit out of the loop. If the break statement is used inside a nested loop (loop inside another loop), it will terminate the innermost loop.
In the following example, we have two loops. The outer for loop iterates the first four numbers using the range() function, and the inner for loop also iterates the first four numbers. If the outer number and a current number of the inner loop are the same, then break the inner (nested) loop.
for i in range(4): for j in range(4): if j == i: break print(i, j)
As you can see in the output, no rows contain the same number.
Continue Nested loop
The continue statement skip the current iteration and move to the next iteration. In Python, when the continue statement is encountered inside the loop, it skips all the statements below it and immediately jumps to the next iteration.
In the following example, we have two loops. The outer for loop iterates the first list, and the inner loop also iterates the second list of numbers.
If the outer number and the inner loop’s current number are the same, then move to the next iteration of an inner loop.
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)
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 same numbers multiplying to each other.
Single Line Nested Loops Using List Comprehension
For example, if you had two lists and want to get all combinations of them, To achieve this, you need to use two nested loops as mentioned below.
first = [2, 3, 4] second = [20, 30, 40] final = [] for i in first: for j in second: final.append(i+j) print(final)
You can write more fast and compact code using the list compression and nested loop like as shown below.
first = [2, 3, 4] second = [20, 30, 40] final = [i+j for i in first for j in second] print(final)
How to write it:
- First, Write an outer for loop that will iterate the first list like [for i in first]
- Next, Write an inner loop that will iterate the second list after the outer loop like [for i in first for j in second]
- Last, calculate the addition of the outer number and inner number like [i+j for i in first for j in second]
- At last, store result in a new list like final = [i+j for i in first for j in second]
Let’s see more such examples.
In this example, we will use two for loops in list Comprehension and the final result would be a list of lists. we will not include the same numbers in each list. we will filter them using an if condition.
final = [[x, y] for x in [10, 20, 30] for y in [30, 10, 50] if x != y] print(final)
[[10, 30], [10, 50], [20, 30], [20, 10], [20, 50], [30, 10], [30, 50]]
Nested while Loop in Python
In Python, The while loop statement repeatedly executes a code block while a particular condition is true. We use w a while loop when number iteration is not fixed.
In this section, we will see how to use a while loop inside another while loop.
The syntax to write a nested while loop statement in Python is as follows:
while expression: while expression: statement(s) statement(s)
In this example, we will print the first 10 numbers on each line 5 times.
12345678910 12345678910 12345678910 12345678910 12345678910
for loop inside While loop
Sometimes it is helpful to use one type of loop inside another. we can put a for loop inside the while loop.
Assume we wanted to print all perfect numbers from 1 to 100
- Here we will iterate the first 100 numbers using a while loop
- In each iteration of the outer while loop, the inner for loop execute from 1 up to the current outer number to check if the current number is a perfect number.
print('Show Perfect number fom 1 to 100') n = 2 # outer while loop while n
When To Use a Nested Loop in Python?
- Nested loops are handy when you have nested arrays or lists that need to be looped through the same function.
- When you want to print different star and number patterns using rows can columns
Keep the time complexity in mind. Let’s understand this with examples on how nested for loop work in Python.
We use for loop to iterates on the given elements of a sequence or iterable. like for i in list . Here time complexity is O(n) because we are iterating all items from a list.
The number of execution steps (iterations) determines the time complexity of a loop.
When you use a nested loop and both outer and inner loop runs without any if condition in it, the time complexity is O(n^2) because, for all of the n elements, the code is executed n times.
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 + 1
iteration 0: 1 iteration 1: 2 iteration 2: 3 iteration 3: 4 iteration 4: 5 iteration 5: 6
If you give a condition in the inner loop that will stop executing after some elements and not execute all n iterations of the inner loop or outer loop, it will have less time complexity.
Use nested loop when you don’t have any better alternatives, Remember writing efficient and compact code is far better than writing complex code.
Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.
About Vishal
I’m Vishal Hule, Founder of PYnative.com. I am a Python developer, and I love to write articles to help students, developers, and learners. Follow me on Twitter
Related Tutorial Topics:
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 10 questions
- Each Quiz contains 12-15 MCQ
Python continue Statement
We can’t use any option, label or condition with the continue statement.
Python continue Statement Examples
Let’s look at some examples of using the continue statement in Python.
1. continue with for loop
Let’s say we have a sequence of integers. We have to skip processing if the value is 3. We can implement this scenario using for loop and continue statement.
t_ints = (1, 2, 3, 4, 5) for i in t_ints: if i == 3: continue print(f'Processing integer ') print("Done")
2. continue statement with the while loop
Here is a simple example of using continue statement with the while loop.
count = 10 while count > 0: if count % 3 == 0: count -= 1 continue print(f'Processing Number ') count -= 1
3. continue statement with a nested loop
Let’s say we have a list of tuples to process. The tuple contains integers. The processing should be skipped for below conditions.
- skip the processing of tuple if its size is greater than 2.
- skip the execution if the integer is 3.
We can implement this logic with nested for loops. We will have to use two continue statements for implementing above conditions.
list_of_tuples = [(1, 2), (3, 4), (5, 6, 7)] for t in list_of_tuples: # don't process tuple with more than 2 elements if len(t) > 2: continue for i in t: # don't process if the tuple element value is 3 if i == 3: continue print(f'Processing ')
Why Python doesn’t support labeled continue statement?
Many popular programming languages support a labeled continue statement. It’s mostly used to skip the iteration of the outer loop in case of nested loops. However, Python doesn’t support labeled continue statement.
PEP 3136 was raised to add label support to continue statement. But, it was rejected because it’s a very rare scenario and it will add unnecessary complexity to the language. We can always write the condition in the outer loop to skip the current execution.