Skip to Content
Course content

55: Nested Loops and When to Avoid Them

Click on the "Edit" button in the top corner of the screen to edit your slide content.

I've always found that the best way to wrap your head around nested loops is to visualize them as a grid. One loop handles the rows, and the other handles the columns. It sounds simple, but it's where a lot of logic errors—and performance nightmares—actually start.

Let's build something concrete. Imagine we're writing a small script to generate a seating chart for a boutique cinema. We have a few rows, and each row has a set number of seats. We want to print out a visual map of these seats so the staff knows which ones are available.

Designing the Theater Grid

To start, I'll represent our theater as a list of lists. Each inner list is a row of seats, and the strings inside (like "Available" or "Taken") represent the status of each seat. Here is how I'll set up my data:

theater_map = [
    ["Available", "Available", "Taken"],
    ["Available", "Taken", "Available"],
    ["Taken", "Available", "Available"]
]

Now, I need to iterate through this. Since theater_map is a list of lists, a single loop only gets me the row. To get to the individual seats, I need a second loop inside the first one.

The Classic Indentation Trap

I'll be honest: even after years of doing this, I still occasionally mess up the indentation when I'm sketching out a nested loop quickly. Watch what happens when I try to print the row number and the seat status:

row_count = 1
for row in theater_map:
    for seat in row:
        print(f"Row {row_count}: {seat}")
    row_count += 1
    print("--- End of Row ---")

Wait, that's not quite right. If I run this, it prints the row number for every single seat. While that works, it's cluttered. What I actually wanted was to print the row header once, and then list the seats under it. I accidentally put my logic too deep in the nested structure.

Let's fix that. I'll move the row announcement outside the inner loop, but keep it inside the outer loop:

row_count = 1
for row in theater_map:
    print(f"Checking Row {row_count}...") # Now this only runs once per row
    for seat in row:
        print(f"  Seat status: {seat}")
    row_count += 1
    print("-" * 20)

Now the output is clean. The outer loop picks a row, the inner loop "exhausts" every seat in that row, and then we move back to the outer loop for the next row.

Knowing When to Walk Away from Nested Loops

Here is the part where I want you to be careful. Nested loops are convenient, but they are computationally expensive. In computer science, we talk about "Time Complexity." A nested loop usually means you're dealing with O(n²), or quadratic time.

In our cinema example, it doesn't matter. We have 9 seats. But what if you were processing a database of 100,000 users, and for every user, you looped through another list of 100,000 transactions to find a match? That's 10 billion operations. Your program will hang, and your users will hate you.

If you find yourself nesting a third or fourth loop, stop. That's a massive red flag. Usually, you can avoid this by using a dictionary (a hash map) to look up data instantly instead of looping through a list to find a value. If you can turn a "loop inside a loop" into "one loop and one dictionary lookup," you've just turned a slow program into a fast one.




📋 Practical Task

The Warehouse Inventory Audit

You've been handed a dataset representing a warehouse. The warehouse is organized by aisles, and each aisle contains bins. Each bin contains a list of items.

warehouse = [
    ["Wrench", "Hammer", "Screwdriver"], # Aisle 0
    ["Drill", "Saw", "Level"],           # Aisle 1
    ["Tape", "Glue", "Paint"]            # Aisle 2
]

Your Task: Write a script using nested loops to search for a specific item (e.g., "Saw"). Your program should loop through the aisles and then the bins. Once it finds the item, it should print the exact location in this format: "Item found in Aisle X, Bin Y" (where X and Y are the indices).

Bonus Challenge: Add a break statement to ensure that once the item is found, the program stops searching immediately rather than continuing through the rest of the warehouse.

Rating
0 0

There are no comments for now.

to be the first to leave a comment.