Nested Loops
In Python, you can nest loops, which means you can use one or more loops inside another loop. This allows you to create more complex patterns of repetition and iterate over multiple dimensions of data. The basic syntax for nested loops is as follows:
for outer_variable in outer_sequence:
# Outer loop code
for inner_variable in inner_sequence:
# Inner loop code
Here's a more detailed breakdown:
- The outer loop is defined using the
for
statement, and it iterates over anouter_sequence
. - Inside the outer loop, there is an inner loop, also defined with the
for
statement, which iterates over aninner_sequence
. - The indented code block following each
for
statement represents the body of the loop.
Example with Nested for
Loops:
for i in range(3):
for j in range(2):
print(f"({i}, {j})")
In this example, there is an outer loop that iterates over the values 0, 1, and 2, and for each value of i
, there is an inner loop that iterates over the values 0 and 1. The output will be:
(0, 0)
(0, 1)
(1, 0)
(1, 1)
(2, 0)
(2, 1)
Example with Nested while
Loops:
i = 0
while i < 3:
j = 0
while j < 2:
print(f"({i}, {j})")
j += 1
i += 1
This example achieves the same result as the previous one but using while
loops instead of for
loops.
Example with Nested Loop for Matrix Multiplication:
matrix_a = [[1, 2], [3, 4]]
matrix_b = [[5, 6], [7, 8]]
result = [[0, 0], [0, 0]]
for i in range(len(matrix_a)):
for j in range(len(matrix_b[0])):
for k in range(len(matrix_b)):
result[i][j] += matrix_a[i][k] * matrix_b[k][j]
for row in result:
print(row)
This example demonstrates nested loops to perform matrix multiplication. The result is a new matrix obtained by multiplying two input matrices, matrix_a
and matrix_b
.
When using nested loops, it's important to keep track of the indentation to correctly represent the scope of each loop. Nested loops are commonly used in situations where you need to iterate over multiple dimensions of data, such as matrices, grids, or nested lists.