Python Nested Loops


Nested Loops in Python

A nested loop is a loop inside another loop. In Python, you can nest for loops, while loops, or even combine for and while loops together. Nested loops are useful when you need to perform complex iterations, such as when working with multi-dimensional data (like matrices or lists of lists).

Syntax

for outer_variable in outer_iterable: for inner_variable in inner_iterable: # Code block to execute for each iteration of inner and outer loop
  • The outer loop runs first.
  • For each iteration of the outer loop, the inner loop runs completely.
  • The process repeats until all iterations of both loops are completed.

Example 1: Nested for Loops

for i in range(3): # Outer loop for j in range(2): # Inner loop print(f"i = {i}, j = {j}")

Output:

i = 0, j = 0 i = 0, j = 1 i = 1, j = 0 i = 1, j = 1 i = 2, j = 0 i = 2, j = 1

In this example:

  • The outer loop (for i in range(3)) iterates 3 times, with i taking the values 0, 1, and 2.
  • The inner loop (for j in range(2)) iterates 2 times for each value of i, with j taking the values 0 and 1.

Example 2: Nested while Loops

i = 1 while i <= 3: # Outer loop j = 1 while j <= 2: # Inner loop print(f"i = {i}, j = {j}") j += 1 i += 1

Output:

i = 1, j = 1 i = 1, j = 2 i = 2, j = 1 i = 2, j = 2 i = 3, j = 1 i = 3, j = 2

In this example:

  • The outer while loop (i <= 3) runs 3 times.
  • For each iteration of the outer loop, the inner while loop (j <= 2) runs twice.

Example 3: Nested for and while Loops

You can mix for and while loops in a nested structure.

i = 1 for j in range(1, 4): # Outer for loop while i <= 2: # Inner while loop print(f"i = {i}, j = {j}") i += 1

Output:

i = 1, j = 1 i = 2, j = 1

Here:

  • The outer for loop runs 3 times, but the inner while loop only runs twice because i increments and causes the condition i <= 2 to become False after 2 iterations.

Example 4: Nested Loops with a List of Lists (Matrix)

Nested loops are commonly used to work with 2D arrays (lists of lists).

matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] for row in matrix: # Outer loop iterates over rows for item in row: # Inner loop iterates over elements in each row print(item, end=" ") print() # To print each row on a new line

Output:

1 2 3 4 5 6 7 8 9

Here:

  • The outer loop iterates over each row of the matrix.
  • The inner loop iterates over each element in the current row, printing them.

Example 5: Using break and continue in Nested Loops

You can use break and continue within nested loops to control the flow of execution.

Example with break:

for i in range(3): for j in range(3): if j == 1: break # Break the inner loop when j equals 1 print(f"i = {i}, j = {j}")

Output:

i = 0, j = 0 i = 1, j = 0 i = 2, j = 0

In this example, the inner loop terminates when j equals 1, but the outer loop continues to run.

Example with continue:

for i in range(3): for j in range(3): if j == 1: continue # Skip the iteration when j equals 1 print(f"i = {i}, j = {j}")

Output:

i = 0, j = 0 i = 0, j = 2 i = 1, j = 0 i = 1, j = 2 i = 2, j = 0 i = 2, j = 2

Here, the inner loop skips printing j = 1, but continues with the next iteration.


Key Points About Nested Loops:

  • The outer loop executes first, and for each iteration of the outer loop, the inner loop executes completely.
  • Nested loops are useful for working with multi-dimensional data (e.g., matrices, lists of lists, tables, etc.).
  • The time complexity of nested loops increases with each level of nesting, so they should be used cautiously in large datasets to avoid performance issues.

Nested loops are powerful tools but can lead to complex code and high computational costs if used excessively, so understanding their structure and application is important.