Concepts / Nested Loops in Python

Nested Loops in Python

You will see that we have two for loops. The outer loop is reading the lines of the file and the inner loop is iterating through each of the words on that particular line. This is an example of a pattern called nested loops because one of the loops is the outer loop and the other loop is the inner loop.

  • Programming

Two Levels of Repetition

A nested loop is a loop placed inside another loop. The outside loop is called the outer loop, and the loop inside it is called the inner loop. A useful way to recognize this pattern is to imagine processing a file one line at a time and then processing the words within the currently selected line.

containsOuter loopfile linesInner loopwords in one line
How is the inner loop contained inside the outer loop, and what does each loop iterate over?

Selecting a Line, Then Its Words

In the file-processing pattern described by the source, the outer loop reads the lines of the file. After the outer loop selects one particular line, the inner loop iterates through the words on that line. The inner loop is therefore working on a smaller part of the data chosen by the outer loop.

outer loop selectsinner loop visitsInput filelinesSelected lineone lineWordswithin selected line
How does the program move from the file's lines to the individual words within each selected line?

Counting Words Across Lines

Imagine an input file with three lines. The first line contains two words, the second contains three words, and the third contains one word. A nested-loop pattern processes every word.

First outer-loop selection: The outer loop selects the first line. The inner loop visits both words on that line before the outer loop can select another line.

Second outer-loop selection: The outer loop selects the second line. The inner loop starts again for this newly selected line and visits its three words.

Third outer-loop selection: The outer loop selects the third line. The inner loop starts again and visits the one word on that line.

Total coverage: The inner-loop visits are 2, then 3, then 1, so every word on every line has been included in the processing.

The nested loops provide complete word coverage across all three lines.

Tracing the Execution Order

The order of execution is not outer-loop step, inner-loop step, outer-loop step, inner-loop step. Instead, one outer-loop selection starts a complete inner-loop traversal. Only after that inner traversal finishes does the outer loop move to its next line.

selectspasses line toafter all wordsouter loop continuesselects another lineFile linesouter loopSelected lineWordsinner loopInner loop completeNext line
What happens next when the outer loop selects a line, and when does the inner loop finish before the outer loop continues?

What do you think happens?

Suppose the outer loop has selected a line containing three words. Does the outer loop select the next line after the first word, or after all three words have been visited?

  • After the first word
  • After all three words
  • At the same time as the first word
Reveal answer

Answer: After all three words

The inner loop runs to completion each time the outer loop runs once. Therefore, all words on the selected line are visited before the outer loop continues.

Starting Again for Each Line

When the outer loop moves to the next line, the inner loop begins another traversal. It is not continuing through the words from the previous line. It is processing the words belonging to the newly selected line. This restart is what lets the combined loops cover every word on every line rather than only the words on one line.

inner loop visitsafter completioninner loop visits againLine 1words 1 to NWords on Line 1inner traversalLine 2words 1 to NWords on Line 2new inner traversal
What changes when the outer loop moves to the next line, and why does the inner loop start iterating through that line's words again?
Outer-loop selectionInner-loop workWhat happens next
One particular lineVisit every word on that lineMove to the next line after completion
The next lineStart a new traversal of that line's wordsMove onward after completion

The inner loop is repeated for each line selected by the outer loop.

Mistakes Beginners Make

  • Treating the two loops as alternating one step at a time

    The inner loop runs to completion for the current outer-loop selection.

    Fix: Trace all words on the selected line before moving the outer loop to its next line.

  • Forgetting what the inner loop is processing

    In the described pattern, the inner loop iterates through the words on the particular line selected by the outer loop.

    Fix: Ask which line the outer loop selected, then identify the words belonging to that line.

  • Counting only lines instead of words

    The file has lines, but the inner loop is needed to visit the words within each line.

    Fix: Account for the inner-loop traversal separately for every outer-loop line.

Practice the Trace

EASY

Consider three lines: the first contains one word, the second contains two words, and the third contains two words. Describe the order in which the nested-loop pattern processes the lines and their words. State when the outer loop is allowed to continue to the next line.

Hints
  • Begin with the first line selected by the outer loop.
  • Finish the inner-loop traversal for that line before moving on.
  • Repeat the same reasoning for the second and third lines.

Practice Solution

Trace three lines containing one word, two words, and two words.

First line: The outer loop selects the first line, and the inner loop visits its one word.

Second line: After the first inner traversal is complete, the outer loop selects the second line, and the inner loop visits both of its words.

Third line: After the second inner traversal is complete, the outer loop selects the third line, and the inner loop visits both of its words.

The processing order covers one word on the first line, then two words on the second line, then two words on the third line. The outer loop advances only after each corresponding inner traversal finishes.

Nested Loop Checklist

  • A nested loop has one or more loops inside another loop.
  • The outer loop selects the larger units of data; in the file example, those units are lines.
  • The inner loop processes the smaller units within the current outer-loop selection; in the file example, those units are words.
  • The inner loop runs to completion for each single run of the outer loop.
  • Together, the loops can count every word on every line of an input file.

Key Takeaways

  • Nested loops place one loop inside another.
  • The outer loop selects a line, while the inner loop iterates through the words on that line.
  • The inner loop completes before the outer loop selects its next line.
  • The inner traversal begins again for each newly selected line.
  • This structure ensures that every word on every line can be processed.