liveBook · Manning

Nested loop

As explained in Practices of the Python Pro

A nested loop is a loop construct placed inside the body of another loop, causing repeated iteration across multiple levels.

A nested loop places one loop inside another. When each item must be compared with every other item, the repeated work can grow proportionally to the square of the input size, or O(n²). section 4.1.2

Checking for duplicate items

The outer loop selects an item, while the inner loop compares it with every item in the sequence. The function returns early when it finds a duplicate; otherwise, its worst case examines the full list. section 4.1.2

def has_duplicates(sequence):
    for index1, item1 in enumerate(sequence):        #1
        for index2, item2 in enumerate(sequence):    #2
            if item1 == item2 and index1 != index2:  #3
                return True
    return False

Inspect the Python implementation to see how the outer and inner loops compare items and avoid matching an item with itself. section 4.1.2

How Practices of the Python Pro covers it

How deep it goes
Explains the repeated comparisons, early termination, and worst-case O(n²) behavior without extending into optimization techniques.
Examples
Demonstrates duplicate detection with Python loops over a sequence.
What you can do after
Evaluate nested-loop code by recognizing its potential quadratic worst-case running time.
How it connects
Connects nested loops with time complexity, Big O notation, and worst-case analysis.

Also explained in

Compare how 3 books explain nested loop →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Practices of the Python Pro. The section links point to the parts of the book it draws on.