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.
Get Your Code: Click here to download the free sample code that you’ll use to learn about nested loops in Python.
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 PythonNested 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 alist
or arange
, 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:
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:
>>> 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:
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: