A nested for loop in Python refers to placing one for loop inside another. This is useful when you need to work with multi-dimensional data, such as matrices (2D arrays) or when performing tasks that require multiple levels of iteration.
Syntax of Nested for Loop:
for outer_variable in outer_sequence:
for inner_variable in inner_sequence:
# Code to execute
Outer loop: Iterates through the outer sequence (like a list, range, etc.).
Inner loop: For each iteration of the outer loop, the inner loop runs through its own sequence.
Example 1: Basic Nested for Loop
This example shows a nested for loop that prints all combinations of two ranges.
for i in range(1, 4): # Outer loop
for j in range(1, 4): # Inner loop
print(f"i = {i}, j = {j}")
Output:
i = 1, j = 1
i = 1, j = 2
i = 1, j = 3
i = 2, j = 1
i = 2, j = 2
i = 2, j = 3
i = 3, j = 1
i = 3, j = 2
i = 3, j = 3
Here:
The outer loop iterates through the numbers 1 to 3.
For each value of i, the inner loop iterates through 1 to 3, producing all combinations.
Example 2: Nested for Loop with Lists
Let’s say you have a list of lists (a 2D list or matrix), and you want to iterate over each element.
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for row in matrix: # Outer loop for each row
for num in row: # Inner loop for each number in the row
print(num, end=" ")
print() # Print a newline after each row
Output:
1 2 3
4 5 6
7 8 9
Here:
The outer loop iterates over each list (row) in the matrix.
The inner loop iterates through each number in the row and prints it.
Example 3: Nested for Loop with Break and Continue
You can also use break and continue inside nested loops.
for i in range(1, 4):
for j in range(1, 4):
if j == 2:
break # Exit the inner loop when j equals 2
print(f"i = {i}, j = {j}")
Output:
i = 1, j = 1
i = 2, j = 1
i = 3, j = 1
Here:
The inner loop breaks when j == 2, so for each iteration of i, the inner loop prints only j = 1.
Example 4: Nested for Loop with Different Range Lengths
You can have different lengths for the ranges in the outer and inner loops.
for i in range(1, 3): # Outer loop with range 1 to 2
for j in range(1, i + 1): # Inner loop with range depending on i
print(f"i = {i}, j = {j}")
Output:
i = 1, j = 1
i = 2, j = 1
i = 2, j = 2
Here:
The outer loop runs from 1 to 2, and for each value of i, the inner loop runs from 1 to i.
For i = 1, the inner loop runs once, and for i = 2, the inner loop runs twice.
Example 5: Using Nested Loops to Print a Pattern
Nested loops are often used for printing patterns, like stars (*) or numbers.
for i in range(5): # Outer loop for rows
for j in range(i + 1): # Inner loop for printing stars in each row
print("*", end=" ")
print() # Print a newline after each row
Output:
*
* *
* * *
* * * *
* * * * *
Here:
The outer loop controls the number of rows, from 0 to 4.
The inner loop prints the number of stars, increasing with each iteration of the outer loop.
Key Points About Nested for Loops:
Efficiency: Nested loops can increase the time complexity of your program. If you have an outer loop with n iterations and an inner loop with m iterations, the total number of iterations is n * m.
Indentation: Proper indentation is crucial in nested loops. The inner loop needs to be indented inside the outer loop.
Multiple Levels: You can have more than two levels of nesting, but too many nested loops can make your code harder to read and inefficient.
Use Cases: Nested loops are commonly used for working with multi-dimensional data (like matrices), creating patterns, or processing combinations of items in different sequences.
Good Practices:
Limit the depth of nesting: While nesting is powerful, excessive nested loops can make your code harder to manage and less efficient.
Optimize: When working with large datasets or complex loops, consider using list comprehensions or more efficient algorithms.
Readability: Use clear variable names and comment where necessary to ensure the nested loop structure is understandable.
Let me know if you'd like to dive deeper into any part of nested loops or need more examples! 😊
0 Comments