AlgoMaster Logo

Nested Loops

Last Updated: January 3, 2026

6 min read

Imagine you need to process a grid of data, like a chess board or a 2D array of pixel values for an image. In these cases, using nested loops is often the simplest approach.

Let’s dive right in!

What Are Nested Loops?

At a high level, a nested loop is simply a loop inside another loop. The outer loop runs once for each iteration of the inner loop, making it a powerful structure for working with multi-dimensional data.

Here's the basic syntax for a nested loop using a for loop:

In this structure, for each item in outer_iterable, the inner loop goes through all items in inner_iterable. This means if the outer loop runs five times and the inner loop runs three times, the total number of iterations will be 15.

Example: Simple Nested Loop

Let’s look at a simple example where we use nested loops to create a multiplication table.

In this example, i represents the current row, while j represents the current column. The result will be a 5x5 multiplication table printed neatly.

Why Use Nested Loops?

Nested loops allow you to perform more complex operations on data structures. Whenever you're dealing with collections that have multiple dimensions, such as matrices or grids, nested loops become invaluable.

Use Cases for Nested Loops

Nested loops are especially handy in various scenarios. Here are a few common applications:

1. Working with 2D Arrays

Consider a situation where you need to traverse a matrix. Each element can be accessed using two indices: one for the row and one for the column.

In this example, the outer loop iterates through each row, while the inner loop goes through each column of the current row, printing each element.

2. Creating Combinations

Nested loops can also be useful for generating combinations of values. Let’s say you want to create a list of all possible pairs from two lists.

This will produce a list of tuples representing all possible combinations of elements from list1 and list2.

3. Finding Duplicates

Another common use case is identifying duplicates in a dataset. You might want to check a list of names to see if any are repeated.

Here, the inner loop checks each name against every other name, starting from the next index to avoid redundant comparisons.

Performance Considerations

While nested loops are powerful, they can also lead to performance issues, especially with large datasets. The time complexity of nested loops is multiplicative. If the outer loop runs n times and the inner loop runs m times, the total time complexity is O(n * m).

Example: Performance Impact

To illustrate the performance impact, let’s consider a case where we need to find the sum of all elements in a large 2D array.

If you run this code, you’ll notice it takes a while to compute the sum. If your dataset doubles in size, this could lead to a fourfold increase in computation time.

Optimizing Nested Loops

Whenever possible, consider optimizing your nested loops. Here are a couple of strategies:

  • Use built-in functions: Python's built-in functions (like sum(), map(), etc.) can often replace nested loops and are optimized under the hood.
  • Reduce iterations with conditions: If you can set conditions to skip unnecessary iterations, this can significantly speed up your loops.

For example, in the duplicates scenario, we could use a set to track seen names, which would reduce the time complexity to O(n):

This approach is generally much faster for larger datasets.

Edge Cases and Common Pitfalls

When working with nested loops, there are some edge cases and common pitfalls to keep in mind:

1. Empty Iterables

If either the outer or inner iterable is empty, the inner loop won’t execute at all. Ensure you handle these cases gracefully, particularly if your code depends on the values from these loops.

2. Indentation Errors

Python relies on indentation to define scope. Ensure your loops are correctly indented, or you might encounter unexpected behavior or syntax errors.

3. Infinite Loops

Be careful with conditions inside your loops. If you’re modifying the loop variable within the loop without proper control, you could inadvertently create an infinite loop.

4. Mutating Lists During Iteration

Modifying the list you’re iterating over can lead to unexpected behavior. For instance, if you remove items from a list while iterating through it, you might skip elements.

To safely remove items, consider iterating over a copy: