Nested Loops with Python

Nested Loops

Concept

Nested loops are loops placed inside another loop. They allow you to handle multidimensional data structures, such as matrices or two-dimensional arrays, or perform repetitive operations that require multiple levels of iteration.

Syntax 

for outer_variable in outer_iterable:
    for inner_variable in inner_iterable:
        # Code to execute for each combination
  •  outer_variable: The variable of the outer loop.
  • outer_iterable: The iterable for the outer loop.
  • inner_variable: The variable of the inner loop.
  • inner_iterable: The iterable for the inner loop.

Behavior

  • Execution: The inner loop executes completely for each iteration of the outer loop. This means that for each item in the outer loop’s iterable, the inner loop iterates over all its items.
  • Levels of Nesting: You can nest loops at multiple levels, but this can make the code more complex and harder to read.

Examples

Printing a Multiplication Table

Example: 

for i in range(1, 4):
    for j in range(1, 4):
        print(f"{i} * {j} = {i * j}")
    print("-----")

Explanation:

  • The outer loop iterates over the values 1, 2, 3.
  • For each value of i, the inner loop iterates over 1, 2, 3.
  • This results in a multiplication table from 1 to 3.
  • The output will be:
1 * 1 = 1
1 * 2 = 2
1 * 3 = 3
-----
2 * 1 = 2
2 * 2 = 4
2 * 3 = 6
-----
3 * 1 = 3
3 * 2 = 6
3 * 3 = 9
-----

Iterating Over a 2D Matrix

Example: 

matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]
for row in matrix:
    for item in row:
        print(item, end=" ")
    print()

Explanation:

  • The outer loop iterates over each row of the matrix.
  • The inner loop iterates over each item in the row.
  • Items are printed in a line for each row of the matrix.
  • The output will be: 
1 2 3
4 5 6
7 8 9

Creating a Star Pattern

Example: 

n = 5
for i in range(n):
    for j in range(i + 1):
        print("*", end="")
    print()

Explanation:

  • The outer loop iterates from 0 to 4.
  • The inner loop prints * based on the value of i, increasing each line.
  • This creates a triangular pattern of stars.
  • The output will be: 
*
**
***
****
*****

Points to Note

  • Performance: Nested loops can lead to increased complexity, especially if nested at multiple levels. For example, a two-level nested loop has a time complexity of O(n^2). Ensure to optimize nested loops to avoid performance bottlenecks.
  • Readability: Using nested loops can make the code more complex. Make sure the code remains readable and well-commented for better understanding.
  • Common Applications: Nested loops are often used for iterating over multidimensional data structures, generating patterns, and performing calculations that require multiple levels of iteration.

Conclusion

Nested loops are a powerful tool for managing multidimensional data or performing complex repetitive operations. While they offer great flexibility, it’s important to use them carefully to avoid performance issues and maintain code readability.

Laisser un commentaire

Votre adresse e-mail ne sera pas publiée. Les champs obligatoires sont indiqués avec *

Facebook
Twitter
LinkedIn
WhatsApp
Email
Print