Python Master Course V2 — 027. Nested Loops
SMARTYFY ACADEMY · MODULE 03 · LESSON 027 OF 200
Nested Loops
Estimated study: 60–90 minutes · Prerequisite: Lesson 026 and preceding Python foundations.
Reason about two-dimensional iteration and complexity.
Video lesson
Video not available yet. This position is reserved for a verified lesson video link or player. The written lesson can be completed without it.
Learning outcomes
- Trace nested loops and explain which loop a break or continue affects.
- Trace program state and predict the output.
- Recognize common errors and boundary conditions.
- Apply the concept to a complete practical project.
- Write independent tests and justify results.
Understand the technique
One complete inner loop for each outer item
A nested loop is a loop inside another loop’s body. Use it to visit every cell in a grid, each item within every order, or every pairing of two small collections. The outer loop chooses a group or row. For that choice, the inner loop completes its iterations before the outer loop advances. This differs from zip, which pairs corresponding items.
Indentation determines how often a statement runs: the inner body runs once per pair; a statement after the inner loop but inside the outer body runs once per row; a statement after both loops runs once.
Trace a two-by-three seating block
for row in range(1, 3):
for seat in range(1, 4):
print(f"R{row}-S{seat}")
print("Row complete")
print("Block complete")
Expected output:
R1-S1
R1-S2
R1-S3
Row complete
R2-S1
R2-S2
R2-S3
Row complete
Block complete
The inner range starts at seat 1 for each row. There are six seat lines, two row messages, and one final message. Keep the two variable names distinct.
Count the work before increasing the dimensions
A rectangular grid with r rows and c columns executes the inner body r × c times. Doubling both dimensions quadruples the work and the number of stored labels. For positive dimensions, the traversal is described as O(r × c). Outer-loop overhead still exists when there are rows but zero columns. Printing directly avoids storing the result list, but still visits every cell.
Not every nested loop traverses a full rectangle. When inner lengths vary, add those lengths rather than multiplying blindly. Break exits only its nearest loop; continue also affects only the loop directly containing it. Reversing the loop order can produce the same labels in a different order.
Initialize an accumulator before both loops to retain earlier rows. Test one row, one column, zero dimensions, and a two-by-three block. Check order as well as count.
Runnable example and expected output
Setup: Python 3.10 or newer, standard library only. Save the following as lesson_027.py and run python lesson_027.py (or python3).
for row in range(1,3):
for col in range(1,4):
print(row,col)
Expected output:
1 1 1 2 1 3 2 1 2 2 2 3
Walkthrough: Identify the initial variable values, follow the control flow in execution order, and write down every printed result. Change one input, predict the new output and then run the modified program.
Project: build seat labels
The input contract is two nonnegative integers. Booleans are rejected. Zero in either dimension produces no seats; negative dimensions are rejected. The raise statements provide a limited preview of errors; exception handling is studied separately.
def seats(rows, columns):
if type(rows) is not int or type(columns) is not int:
raise ValueError("Seat dimensions must be integers")
if rows < 0 or columns < 0:
raise ValueError("Seat dimensions must be nonnegative")
labels = []
for row in range(1, rows + 1):
for column in range(1, columns + 1):
labels.append(f"R{row}-S{column}")
return labels
print(seats(2, 2))
print(seats(2, 0))
Expected output:
['R1-S1', 'R1-S2', 'R2-S1', 'R2-S2']
[]
Testing plan: try (1, 1), (0, 3), (3, 0), and (2, 3). Check label order and count. Separately confirm that a negative, decimal, or Boolean dimension raises ValueError.
Common mistakes and professional practices
- Confusing an expression’s value with a side effect.
- Skipping validation of inputs and collection sizes.
- Misreading the order of operations or changes to state.
- Forgetting to test zero, empty, minimum and maximum cases.
- Using overly complicated logic instead of descriptive intermediate variables.
Debugging approach: Print the relevant state, compare each step with the expected result, isolate the first divergence, correct the underlying rule, and rerun all cases.
Think, trace, and solve
Attempt each question before revealing its answer. Explain your reasoning as well as the result.
1. Count and order the pairs
for letter in ["A", "B"]:
for number in [1, 2, 3]:
print(letter, number)
Predict the output and number of inner-body executions.
Optional hint
Complete every number for A before moving to B.
Reveal answer and reasoning
Expected output:
A 1
A 2
A 3
B 1
B 2
B 3
There are 2 × 3 = 6 executions. The inner loop completes for A before the outer loop selects B.
2. Locate the break
for row in [1, 2]:
for column in [1, 2, 3]:
if column == 2:
break
print(row, column)
print("Done")
Does break stop both rows? Predict the output.
Optional hint
Identify the loop that directly contains break.
Reveal answer and reasoning
Expected output:
1 1
2 1
Done
Break exits only the column loop. Row 2 starts its own column traversal.
3. Find the accumulator reset
Why would moving labels = [] inside the outer loop make seats(2, 2) return only row 2? Where should initialization go?
Optional hint
Track when a new empty list is created.
Reveal answer and reasoning
Each outer iteration discards the earlier list reference and starts empty. Initialize before the outer loop to retain all four labels, in row order.
4. Check zero dimensions
Compare seats(0, 3) and seats(3, 0). Do the results and outer-iteration counts match?
Optional hint
A row can execute even if it has no columns.
Reveal answer and reasoning
Both return []. The first has zero outer iterations; the second has three outer iterations and no inner iterations. Equal output does not imply identical control flow.
5. Estimate growth
A grid grows from 20 × 30 to 40 × 60. Count the cell-body executions. Does storing every label use constant extra space?
Optional hint
Multiply the dimensions and compare the two products.
Reveal answer and reasoning
The counts are 600 and 2,400, a fourfold increase. Stored labels grow with the number of cells. Printing directly avoids the result list but still traverses all 2,400 cells.
Mastery checkpoint
Before advancing, explain the main concept without notes, predict the example output, run the project, and create at least three independent tests. If your results differ, revisit the debugging section.
Summary: Reason about two-dimensional iteration and complexity. Reliable programs combine clear logic, appropriate validation and repeatable testing.
Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.