Python
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax and Data Types
-
Section 3: Collections
-
39: Set Operations: Union, Intersection, Difference
-
Section 4: Control Flow
-
Section 5: Functions
-
Section 6: Turtle Graphics and Early Practice Projects
-
Section 7: Working with Files and I/O
-
Section 8: Regular Expressions
-
Section 9: Object-Oriented Python
-
Section 10: Error Handling
-
Section 11: Modules and Packages
-
Section 12: Iterators, Generators, and Functional Tools
-
Section 13: Decorators and Metaprogramming
-
Section 14: Concurrency and Parallelism
-
Section 15: Working with Dates, Times, and Numbers
-
Section 16: Standard Library Deep Dive I: Data Structures
-
Section 17: Standard Library Deep Dive II: System and Introspection
-
Section 18: Standard Library Deep Dive III: Security and Encoding
-
Section 19: Standard Library Deep Dive IV: Text and Data Utilities
-
Section 20: Networking and Web Basics
-
Section 21: Working with Databases
-
Section 22: Testing and Quality
-
Section 23: Advanced Typing
-
Section 24: Context Managers and Resource Handling
-
Section 25: Text, Unicode, and Binary Data
-
Section 26: More Functional and Iteration Tools
-
Section 27: Data Validation and Configuration
-
Section 28: Working with Images and Media
-
Section 29: Property-Based and Documentation Testing
-
Section 30: Packaging and Deployment
-
Section 31: Performance and Internals
-
Section 32: Design Patterns in Python
-
Section 33: GUI Programming
-
Section 34: Security Basics
-
Section 35: Data Structures and Algorithms
-
Section 36: Practical Projects
-
Section 37: Capstone Projects
-
Section 38: Interview and Algorithm Practice
-
Section 39: Writing Idiomatic Python
55: Nested Loops and When to Avoid Them
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.
There are no comments for now.