0
0
PythonHow-ToBeginner · 3 min read

How to Write Nested For Loop in Python: Syntax and Examples

In Python, a nested for loop is a loop inside another loop. You write it by placing one for loop inside the body of another for loop, each with its own variable and range.
📐

Syntax

A nested for loop in Python has one for loop inside another. The outer loop runs first, and for each iteration of the outer loop, the inner loop runs completely.

  • Outer loop: Runs through its sequence.
  • Inner loop: Runs fully for each outer loop iteration.
  • Variables: Each loop has its own variable to track the current item.
python
for outer_variable in outer_sequence:
    for inner_variable in inner_sequence:
        # code to execute
💻

Example

This example prints pairs of numbers from two lists using a nested for loop. It shows how the inner loop runs completely for each item of the outer loop.

python
list1 = [1, 2]
list2 = ['a', 'b']

for num in list1:
    for letter in list2:
        print(f"{num} - {letter}")
Output
1 - a 1 - b 2 - a 2 - b
⚠️

Common Pitfalls

Common mistakes include:

  • Not indenting the inner loop correctly, which causes syntax errors.
  • Using the same variable name in both loops, which overwrites values and causes bugs.
  • Forgetting that the inner loop runs fully for each outer loop iteration, which can lead to unexpected output.
python
wrong:
for i in range(2):
    for i in range(3):  # wrong variable reuse
        print(i)

correct:
for i in range(2):
    for j in range(3):
        print(i, j)
Output
0 0 0 1 0 2 1 0 1 1 1 2
📊

Quick Reference

ConceptDescription
Outer loopRuns first and controls how many times the inner loop runs
Inner loopRuns completely for each iteration of the outer loop
IndentationInner loop must be indented inside the outer loop
VariablesUse different variable names for each loop

Key Takeaways

A nested for loop is a loop inside another loop, each with its own variable.
Indent the inner loop properly inside the outer loop to avoid errors.
Use different variable names for outer and inner loops to prevent bugs.
The inner loop runs fully for every single iteration of the outer loop.
Nested loops help process combinations or pairs of items easily.