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
Output:
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
Output:
Explanation:
-
The outer loop (
i) represents the table number (from 1 to 5). -
The inner loop (
j) prints the table entries fromitoi×10, usingias the step. -
This avoids code duplication and works dynamically for any number of tables.
Mixing for and while Loops
Output:
How it works:
-
iruns from 1 to 2 (forloop). -
For each
i,jstarts from 1 and runs whilej < 3(whileloop). -
After each inner loop finishes,
"GFG"is printed.
Application: Looping Through a List of Lists
Output:
Explanation:
-
llis 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.