Loading Page Content...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
In programming, data often spans more than a single dimension. Spreadsheets have rows and columns, digital images consist of pixel grids $(x, y)$, game boards (like chess or tic-tac-toe) have coordinate squares, and cinema halls have numbered seats across designated rows.
To process multi-dimensional data structures, Python utilizes nested loops—where one loop resides inside the body of another. In a nested loop construct, the inner loop completes its entire cycle of iterations for every single iteration of the outer loop.
+-------------------------------------------------------------------------------+
| NESTED LOOP REAL-WORLD ANALOGIES |
+-------------------------------------------------------------------------------+
1. PVR MULTIPLEX / CINEMA SEAT ALLOCATION:
- An usher sweeps through an auditorium to check tickets:
Rows: ["Row A", "Row B", "Row C"]
Seats per Row: [Seat 1, Seat 2, Seat 3, Seat 4]
- FOR each row IN Rows: <-- OUTER LOOP
* Announce "Inspecting Row..."
* FOR each seat IN Seats: <-- INNER LOOP
- Check barcode for Seat!
- The usher inspects every seat (1 to 4) before advancing to the next row.
2. THE MECHANICAL WALL CLOCK:
- Outer Loop: Hour Hand (advances 1 step every hour: 1 to 12).
- Inner Loop: Minute Hand (must complete 60 full revolutions per hour).
- Total minute ticks per 12-hour cycle = 12 * 60 = 720 ticks.
+-------------------------------------------------------------------------------+A nested loop can combine for and while loops in any combination. The most common structure is a nested for loop:
If the outer loop runs $M$ times and the inner loop runs $N$ times, the statement inside the inner loop will execute a total of: $$\text{Total Iterations} = M \times N$$
Output:
In Python, a 2D matrix is represented as a list of lists. Nested loops provide the canonical mechanism to traverse every row and cell:
Output:
Pattern printing exercises are a classical computer science technique to master coordinate geometry and nested index relationships:
In a right-angled triangle, the number of columns printed depends directly on the current row number:
Output:
A pyramid requires two inner loops per row: one to print leading spaces, and another to print the stars:
Output:
Every level of nesting multiplies the time complexity of your program:
+----------------+---------------------+-------------------------------+ | NESTING DEPTH | BIG-O COMPLEXITY | ITERATIONS FOR N = 1,000 | +----------------+---------------------+-------------------------------+ | 1 Loop | O(N) Linear | 1,000 steps (~Instant) | | 2 Nested Loops | O(N^2) Quadratic | 1,000,000 steps (~0.05 sec) | | 3 Nested Loops | O(N^3) Cubic | 1,000,000,000 steps (~10 sec) | | 4 Nested Loops | O(N^4) Quartic | 1,000,000,000,000 (~Hours!) | +----------------+---------------------+-------------------------------+
| Best Practice (DO) | Dangerous Anti-Pattern (DON'T) |
|---|---|
DO use distinctive variable names for each loop level (e.g. row, col or student, mark). | DON'T re-use the same variable name in outer and inner loops (for i in ...: for i in ...: overwrites i). |
DO use print() with end="" to construct 2D grid outputs horizontally. | DON'T place expensive operations (like file reads or API calls) inside deep inner loops. |
| DO keep nesting depth to at most 2 levels whenever possible. | DON'T write 4-level nested loops that result in $O(N^4)$ performance degradation. |
break statement inside an inner loop breaks only out of that immediate inner loop, not the outer loop.If you forget to update your loop counter inside a while loop, the condition remains True forever:
Removing or inserting items in a list while looping over it causes skipped elements:
print("Tick") statement execute in the following code?A. 7 times B. 12 times C. 4 times D. 3 times
A. 11 12 21 22 B. 11 22 C. 12 12 D. 1 2 1 2
break statement is encountered inside an inner nested loop?A. Both the inner and outer loops terminate immediately B. Only the inner loop terminates; the outer loop proceeds to its next iteration C. Python restarts the outer loop from index 0 D. A RuntimeError is raised
i for both outer and inner loops like for i in range(3): for i in range(2):?A. Python raises a SyntaxError: duplicate loop target B. The inner loop rebinds i, clobbering the outer loop variable and causing confusing or unexpected loop bounds C. Python automatically renames the inner variable to i_inner D. The inner loop is automatically skipped
A. $O(1)$ B. $O(M + N)$ C. $O(M \times N)$ D. $O(M^N)$
Build an interactive seat layout and reservation engine for a PVR Cinemas auditorium.
The cinema hall consists of 4 rows ("Row A", "Row B", "Row C", "Row D"), each containing 6 seats (numbered 1 through 6).
"O" (Open/Available).[("A", 2), ("A", 3), ("C", 4), ("D", 1)]), use nested loops to update those seats to "[X]" (Booked) and available seats to "[O]".In the next lesson, we will continue your Python learning journey with Break, Continue, Pass (13: Loops).
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
| Previous Lesson | Next Lesson |
|---|---|
| For Loop | Break, Continue, Pass |
Test your understanding of this lesson with 5 questions. Each question has one correct answer.