Lesson 18 of 4045%
(Progress persistence is disabled until Phase 9)
Python
Beginner
Nested Loops
Put loops inside other loops.
Nested Loops
What You’ll Learn
A nested loop is a loop inside a loop. You’ll learn how to use them to iterate over multi-dimensional data.
How it Works
The “inner loop” will be executed one time for each iteration of the “outer loop”.
colors = ["red", "green"]
fruits = ["apple", "banana"]
for color in colors:
for fruit in fruits:
print(color, fruit)
Expected Output:
red apple
red banana
green apple
green banana
Breaking down the execution
- The outer loop starts with
color = "red". - The inner loop starts and goes through all items: “red apple”, then “red banana”.
- The inner loop finishes.
- The outer loop moves to the next item:
color = "green". - The inner loop starts again from the beginning: “green apple”, then “green banana”.
Common Mistakes
- Performance: Be careful with nested loops. If the outer loop runs 1,000 times, and the inner loop runs 1,000 times, the code inside the inner loop runs 1,000,000 times!