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.
Also, Solve:
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 loopCode language: Python (python)
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
forloop uses the range() function to iterate over the first ten numbers - The inner
forloop 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.