Nested loops

Nested Loops in Python

In Python, a loop is used to repeat a block of code as long as a certain condition holds true. A nested loop is a loop placed inside another loop, allowing for more complex and structured iterations.


Problem: Print Multiplication Tables from 1 to 10

We want to print multiplication tables from 1 to 10. That is:

  • Table of 1: 1 2 3 ... 10

  • Table of 2: 2 4 6 ... 20

  • ...

  • Table of 10: 10 20 30 ... 100


Initial Approach: Using Separate Loops

for i in range(1, 11):
print(i, end=" ") print() for i in range(2, 21, 2): print(i, end=" ") print() for i in range(3, 31, 3): print(i, end=" ") print()

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

Problems with this method:

  • Repetitive: You'd need 10 loops to print tables from 1 to 10.

  • Not scalable: If the number of tables changes, so must the code.


Efficient Solution: Using Nested Loops

for i in range(1, 6):
for j in range(i, i * 10 + 1, i): print(j, end=" ") print()

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

Explanation:

  • The outer loop (i) represents the table number (from 1 to 5).

  • The inner loop (j) prints the table entries from i to i×10, using i as the step.

  • This avoids code duplication and works dynamically for any number of tables.


Mixing for and while Loops

for i in range(1, 3):
j = 1 while j < 3: print(i, j) j += 1 print("CSK")

Output:

1 1 1 2 CSK 2 1 2 2 CSK

How it works:

  • i runs from 1 to 2 (for loop).

  • For each i, j starts from 1 and runs while j < 3 (while loop).

  • After each inner loop finishes, "GFG" is printed.


Application: Looping Through a List of Lists

ll = [[10, 20, 30], [40, 50, 60], [70, 80]]
for sublist in ll: for item in sublist: print(item, end=" ") print()

Output:

10 20 30 40 50 60 70 80

Explanation:

  • ll is a list of lists.

  • The outer loop goes through each sublist.

  • The inner loop prints each element in that sublist.


Conclusion:

Nested loops are powerful when dealing with:

  • Tables

  • Grids

  • Lists of lists

  • Any situation requiring repeated inner operations for each outer element

They make your code shorter, cleaner, and much more flexible.

Popular Posts