Nested Loops in Python

Nested Loops in Python

by Amanda Adoyi Updated Reading time estimate 25m basics python

Nested loops in Python allow you to place one loop inside another, enabling you to perform repeated actions over multiple sequences. Understanding nested loops helps you write more efficient code, manage complex data structures, and avoid common pitfalls such as poor readability and performance issues.

By the end of this tutorial, you’ll understand that:

  • Nested loops in Python involve placing one loop inside another, enabling iteration over multiple sequences or repeated actions.
  • Situations where nested loops are a good idea include handling multidimensional data, generating patterns, and performing repetitive tasks with multiple layers of iteration.
  • You can break out of nested loops by using the break statement, which exits the innermost loop when a condition is met.
  • Disadvantages of nested loops include potential performance bottlenecks, poor readability, and variable scoping issues.

This tutorial provides practical examples and optimization techniques for using nested loops effectively in your Python programs.

Take the Quiz: Test your knowledge with our interactive “Nested Loops in Python” quiz. You’ll receive a score upon completion to help you track your learning progress:


Interactive Quiz

Nested Loops in Python

Nested loops allow you to perform repeated actions over multiple sequences, but is there more? Test your understanding of nested loops in Python!

Getting Started With Nested Loops in Python

Loops are fundamental building blocks in programming, allowing you to iterate through actions efficiently. In Python, there are two primary types of loops: the for loop and the while loop. Both serve the same purpose —executing a block of code multiple times—but they differ in how they operate and in their use cases:

  • A for loop iterates over a sequence, such as a list or a range, and executes a block of code for each item. They’re useful when the number of iterations is known beforehand.
  • A while loop runs as long as a specified condition remains true, making it useful when the number of iterations isn’t known in advance.

You create a nested loop by placing one loop inside another. This structure is especially helpful when working with multidimensional data, generating patterns, or handling tasks that involve several layers of repetition.

In a nested loop, the first loop is called the outer loop, and the loop inside is the inner loop. So, for every iteration of the outer loop, the inner loop runs completely before the outer loop moves to the next iteration.

Here’s the basic syntax of a nested loop:

Language: Python Syntax
for outer_variable in outer_iterable:
    for inner_variable in inner_iterable:
        <body>

The outer_iterable must be a list, a dictionary, or some other sequence of items that you can iterate over. The same applies to the inner_iterable. The <body> inside the inner loop contains the code that runs once for each for loop step in the inner_iterable. Since the inner loop is nested inside the outer loop, it runs in full for each iteration of the outer loop.

A good analogy for a nested loop is the hour and minute hands of a clock. The hour hand moves slowly around the clock, completing one full revolution every twelve hours. Meanwhile, the minute hand moves at a much faster rate, completing a revolution every hour. While both hands rotate at different speeds, they work together, each completing their own cycle within the same clock.

Here’s how the clock logic looks in Python code:

Language: Python
>>> for hour in range(0, 24):
...     for minute in range(0, 60):
...         print(f"{hour:02d}:{minute:02d}")
...
00:00
00:01
00:02
  ⋮
23:57
23:58
23:59

As you can see, every time the minute hand completes a cycle, the hour hand moves to the next hour. :02d is a format specifier that ensures the number is printed as a two-digit-wide integer value.

Now that you’ve been introduced to nested loops, it’s time to explore some practical examples. You’ll become familiar with writing programs using nested loops in the following section.

Exploring Practical Examples of Nested Loops

As you just learned, nested loops have a number of use cases. Here, you’ll have a look at a few examples. These examples are interesting and practical, allowing you to have fun as you explore their syntax and semantics.

Printing Patterns With Nested Loops

Being able to print any pattern of your choosing is a fascinating feat in programming. One way you can achieve this is by understanding how nested loops work. The code snippet below builds a sail pattern using a few simple symbols. While this may not seem particularly exciting, consider it a first step toward creating something spectacular—like a spaceship:

Language: Python
 1>>> height = 6
 2>>> sail_patterns = "*#-x+o"
 3>>> for row in range(height):
 4...     pattern = ""
 5...     spacing = " " * (height - row)
 6...     for symbol in sail_patterns:
 7...         pattern += symbol * row + spacing
 8...
 9...     print(pattern)
10...
11
12*     #     -     x     +     o
13**    ##    --    xx    ++    oo
14***   ###   ---   xxx   +++   ooo
15****  ####  ----  xxxx  ++++  oooo
16***** ##### ----- xxxxx +++++ ooooo

Here’s what the code does line by line:

  • Line 1: Sets the height variable, which is an indication of the size of the ship. It controls the number of rows in the pattern.
  • Line 3: Begins the outer for loop, iterating from 0 up to, but not including, height.
  • Line 5: Shifts the pattern to the right, decreasing spaces with increasing rows.
  • Line 6: Starts the inner for loop over the sail_patterns. It’s followed by the body of the loop, which updates the pattern.
  • Line 9: Prints the completed pattern.

This way, the spaceship is essentially built piece by piece. Adding one piece at a time, you could increase its size or expand its structure.

Generating a Multiplication Table

Multiplication tables display the results of numbers multiplied by one another. These tables are commonly used in grade school for quick reviews of multiplication operations. Nested for loops are a great way to generate multiplication tables in Python:

Language: Python
>>> for multiplicant in range(1, 11):
...     for multiplier in range(1, 4):
...         expression = f"{multiplicant:>2d} × {multiplier}"
...         product = multiplicant * multiplier
...         print(f"{expression} = {product:>2d}", end="\t")
...     print()
 1 × 1 =  1      1 × 2 =  2      1 × 3 =  3
 2 × 1 =  2      2 × 2 =  4      2 × 3 =  6
 3 × 1 =  3      3 × 2 =  6      3 × 3 =  9
     ⋮                ⋮               ⋮
 8 × 1 =  8      8 × 2 = 16      8 × 3 = 24
 9 × 1 =  9      9 × 2 = 18      9 × 3 = 27
10 × 1 = 10     10 × 2 = 20     10 × 3 = 30

The example above displays the multiplication of numbers. The outer loop iterates through numbers 1 to 10, while the inner loop iterates through numbers 1 to 3.

For every iteration of the outer loop, the current value is multiplied by each number in the inner loop. After finishing one row, print() moves to the next line. This creates a structured multiplication table. You could give this a go yourself by using different ranges and printing the result.

In the next section, you’ll explore how to use nested loops to sum all the elements in a nested list.

Summing Elements in Multidimensional Lists

Another application of nested loops is processing elements in more than one dimension. A multidimensional or nested list is a list that contains other lists as its elements. To sum all elements in a nested list, you can use nested loops.

Staying true to the theme of space travel, you can picture nested list summation this way:

Language: Python
>>> resource_donators = [
...     [8, 6, 3],
...     [9, 2, 7],
...     [4, 1, 5]
... ]
>>> total_resources = 0
>>> for planet in resource_donators:
...     for resource in planet:
...         total_resources += resource
...
>>> print(f"All resources gathered for interstellar travels: {total_resources}")
All resources gathered for interstellar travels: 45

Here, you use a nested for loop to handle resource collection from altruistic planets in a star system. Each sublist in resource_donators represents a planet, and each number in the sublist represents a unit of a resource—say, something known throughout the galaxy as foodonium. The total_resources is initialized to 0.

The outer loop iterates through each planet, and the inner loop goes through each individual resource, adding it to total_resources. Suppose that one planet provides 8, 6, and 3 units of foodonium. After processing all planets, the final total is printed, and the spaceship can continue on its way.

Next, you’ll take a look at how you can use nested loops to create pairwise combinations.

Creating Pairwise Combinations

When building programs, you may have to work with datasets that require you to make comparisons or work with data in pairs. In the example below, you’ll find a program that generates all possible matchups between players in a friendly game of space ball:

Language: Python
>>> players = ["Bonnie", "Mike", "Raj", "Adah"]

>>> for player1 in players:
...     for player2 in players:
...         print(f"{player1} vs {player2}")
...
Bonnie vs Bonnie
Bonnie vs Mike
Bonnie vs Raj
      ⋮
Adah vs Bonnie
Adah vs Mike
Adah vs Raj
Adah vs Adah

With this approach, you can generate all possible matchups—including self-matchups—demonstrating that pairwise combinations are possible with nested loops. You may have noticed that players are allowed to play against themselves, which you might not want. Click the collapsible section below to learn how to get rid of self matchups in space ball.

You’ll have noticed that space ball allows players to be matched against themselves. Perhaps that’s just the nature of the game, or maybe you’d prefer to prevent that from happening. How could you remove self-matchups from the program above? One solution is to add an if condition to filter them out, as shown in the code below:

Language: Python
>>> players = ["Bonnie", "Mike", "Raj", "Adah"]

>>> for player1 in players:
...     for player2 in players:
...         if player1 != player2:
...             print(f"{player1} vs {player2}")
...
Bonnie vs Mike
Bonnie vs Raj
Bonnie vs Adah
Mike vs Bonnie
Mike vs Raj
Mike vs Adah
Raj vs Bonnie
Raj vs Mike
Raj vs Adah
Adah vs Bonnie
Adah vs Mike
Adah vs Raj

This code example shows one way to generate pairwise combinations while filtering out self-matchups. This pattern comes in handy whenever you’re comparing elements in a group.

As you’ve seen, nested loops make it easy to create pairwise combinations, whether you’re including or filtering out matches. This isn’t only useful in games, but also in real-world scenarios like comparing data entries. With that under your belt, you’ll now take a look at an example that uses while loops in nested situations.

Working With while Loops in Nested Structures

So far, you’ve seen several examples using for loops in nested loops. There are also a number of situations where you’ll prefer to use while loops instead. For example, say that you’re building an app that prints each letter of a word:

Language: Python
>>> while True:
...     word = input("Enter a word (or type 'exit' to stop): ")
...
...     if word == "exit":
...         break
...
...     for letter in word:
...         print(letter)
...
Enter a word (or type 'exit' to stop): foodonium
f
o
o
d
o
n
i
u
m
Enter a word (or type 'exit' to stop): exit
>>>

The example above shows a program that allows a user to type a word at the prompt, with each letter of the word eventually printed to the screen. A break keyword is added to halt the execution of the program when