In Python, a nested loop refers to having one loop inside another. Both loops can be of the same type (for
or while
) or different types. Nested loops are useful for iterating over multi-dimensional data, such as matrices or lists of lists, or performing operations where one set of iterations is dependent on another.
Usage of nested loop
Example 1: Nested for
loops
for i in range(3): # Outer loop
for j in range(2): # Inner loop
print(f"i = {i}, j = {j}")
Explanation: The outer loop (i
) runs 3 times, and for each iteration of i
, the inner loop (j
) runs 2 times. This results in a total of 6 iterations in total.
Output:
i = 0, j = 0i = 0, j = 1
i = 1, j = 0
i = 1, j = 1
i = 2, j = 0
i = 2, j = 1
Example 2: Nested while
loop
i = 1
while i <= 3: # Outer loop
j = 1
while j <= 2: # Inner loop
print(f"i = {i}, j = {j}")
j += 1
i += 1
Explanation: The outer while
loop runs as long as i
is less than or equal to 3, and the inner while
loop runs twice for each value of i
. Each iteration of the inner loop increments j
, and after the inner loop completes, the outer loop increments i
.