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
- 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
Output:
In this example:
- The outer loop (
for i in range(3)
) iterates 3 times, withi
taking the values0
,1
, and2
. - The inner loop (
for j in range(2)
) iterates 2 times for each value ofi
, withj
taking the values0
and1
.
Example 2: Nested while
Loops
Output:
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.
Output:
Here:
- The outer
for
loop runs 3 times, but the innerwhile
loop only runs twice becausei
increments and causes the conditioni <= 2
to becomeFalse
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).
Output:
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
:
Output:
In this example, the inner loop terminates when j
equals 1, but the outer loop continues to run.
Example with continue
:
Output:
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.