0
0
Pythonprogramming~5 mins

Nested for loop execution in Python

Choose your learning style9 modes available
Introduction
Nested for loops help you repeat actions inside other repeated actions, like checking every seat in a theater row by row.
When you want to go through a grid or table, like rows and columns.
When you need to compare every item in one list with every item in another list.
When you want to create combinations of items from two or more groups.
When you want to print patterns, like stars in rows and columns.
When you want to process multi-level data, like a list of lists.
Syntax
Python
for item1 in collection1:
    for item2 in collection2:
        # do something with item1 and item2
The inner loop runs completely for each single run of the outer loop.
Indentation shows which loop is inside the other.
Examples
Prints pairs of numbers where i goes 0 to 1 and j goes 0 to 2 for each i.
Python
for i in range(2):
    for j in range(3):
        print(i, j)
Prints seat labels combining rows and seat numbers.
Python
for row in ['A', 'B']:
    for seat in [1, 2]:
        print(f"Row {row} Seat {seat}")
Sample Program
This program shows how the inner loop runs fully for each step of the outer loop.
Python
for i in range(3):
    for j in range(2):
        print(f"Outer loop i={i}, Inner loop j={j}")
OutputSuccess
Important Notes
Remember that the inner loop finishes all its steps before the outer loop moves to the next step.
Too many nested loops can make your program slow, so use them wisely.
Indentation is very important in Python to show which code belongs to which loop.
Summary
Nested for loops let you repeat actions inside other repeated actions.
The inner loop runs completely for each step of the outer loop.
Use nested loops to work with grids, combinations, or multi-level data.