Python nested loop

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 = 0
i = 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.

Python nested loop – Interview Questions

Q 1: What is a nested loop?

Ans: A loop placed inside another loop.

Q 2: Why are nested loops used?

Ans: To work with multi-dimensional data or repeated patterns.

Q 3: Can for and while loops be nested?

Ans: Yes, any loop can be nested inside another.

Q 4: Which loop runs first in a nested loop?

Ans: The outer loop runs first, then the inner loop.

Q 5: Are nested loops performance-heavy?

Ans: Yes, they can increase execution time.

Python nested loop – Objective Questions (MCQs)

Q1. What is a nested loop in Python?






Q2. How many times will the inner loop execute in the following code?

for i in range(2)
for j in range(3):
print(i, j)






Q3. What will be the output of the following code?

for i in range(2):
for j in range(2):
print("Hello")






Q4. In a nested loop, when a break statement is used inside the inner loop, it:






Q5. What will the following code output?

for i in range(3):
for j in range(2):
print(i, j, end=" ")






Related Python nested loop Topics