In Python, a nested for loop is a loop inside another loop.
It allows you to iterate
over mul ple sequences, or to iterate over a sequence while performing another
itera on inside it. Nested loops are useful for handling tasks that involve mul -
dimensional data structures, such as lists of lists, matrices, or complex itera on
pa erns.
Syntax:
for outer_variable in outer_sequence:
for inner_variable in inner_sequence:
# Code to be executed
The outer loop runs once, and for each itera on of the outer loop, the
inner loop runs completely.
The inner loop can iterate through its en re sequence for each itera on of
the outer loop, which creates a nested structure.
Example 1: Prin ng a 2D matrix
Let’s say you have a list of lists (a 2D matrix), and you want to print each element.
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
for row in matrix: # Outer loop iterates through each row
for element in row: # Inner loop iterates through each element in the row
print(element, end=" ")
print() # To print a new line a er each row
Output:
123
456
789
Example 2: Genera ng all pairs of numbers
In this example, a nested for loop is used to generate all pairs of numbers from
two different lists.
list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
for num in list1: # Outer loop
for char in list2: # Inner loop
print(num, char)
Output:
css
Copy code
1a
1b
1c
2a
2b
2c
3a
3b
3c
Example 3: Nested loops with condi ons
You can also use condi ons inside nested loops to filter out results based on
specific criteria.
for i in range(1, 4): # Outer loop
for j in range(1, 4): # Inner loop
if i != j:
print(f"i = {i}, j = {j}")
Output:
css
Copy code
i = 1, j = 2
i = 1, j = 3
i = 2, j = 1
i = 2, j = 3
i = 3, j = 1
i = 3, j = 2
Considera ons:
Efficiency: Nested loops can quickly become inefficient, especially if the
outer and inner loops have a large number of itera ons. The me
complexity grows exponen ally (O(n^2) for two nested loops).
Indenta on: The inner loop must be indented further than the outer loop
to define the correct scope.