Understanding Nested Loops in Python | Python Tutorials on BeingSkilled

Understanding Nested Loops in Python

Nested loops in Python are loops inside other loops. They allow you to iterate through multiple levels of data and are especially useful for tasks like working with matrices, tables, or complex data structures. Mastering nested loops gives you the ability to write more powerful and structured programs.

In this guide, we'll break down how nested loops work and explore 10 practical, easy-to-understand examples.

What Are Nested Loops?

A nested loop is when one loop runs inside another. The inner loop runs completely every time the outer loop runs once.

Basic Syntax

for i in outer_range:
    for j in inner_range:
        # code block

This can also be done with while loops, or a mix of for and while.

Example 1: Basic Nested for Loop

for i in range(2):
    for j in range(3):
        print(i, j)

This prints all combinations of i and j.

Example 2: Multiplication Table

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

Generates a simple 3x3 multiplication table.

Example 3: Pattern Printing

for i in range(1, 4):
    for j in range(i):
        print("*", end="")
    print()

Prints a triangle pattern using stars.

Example 4: Nested Loop with Lists

matrix = [[1, 2], [3, 4], [5, 6]]

for row in matrix:
    for item in row:
        print(item)

Loops through each row and item in a 2D list.

Example 5: Using break in Nested Loops

for i in range(3):
    for j in range(3):
        if j == 1:
            break
        print(i, j)

Breaks the inner loop when j == 1.

Example 6: Skipping Values with continue

for i in range(2):
    for j in range(3):
        if j == 1:
            continue
        print(i, j)

Skips inner loop value 1, but continues others.

Example 7: Creating a Grid of Coordinates

for x in range(3):
    for y in range(3):
        print(f"({x},{y})", end=" ")
    print()

Displays all (x, y) coordinate pairs in a grid format.

Example 8: Nested while Loops

i = 0
while i < 2:
    j = 0
    while j < 2:
        print(i, j)
        j += 1
    i += 1

Nested while loops work similarly to for loops.

Example 9: Combining for and while Loops

i = 0
for x in range(2):
    while i < 2:
        print(x, i)
        i += 1

Combines a for loop with an inner while loop.

Example 10: Looping Through Dictionary of Lists

data = {"fruits": ["apple", "banana"], "colors": ["red", "blue"]}

for category in data:
    for item in data[category]:
        print(f"{category}: {item}")

Accesses items in nested data structures.


Tips for Using Nested Loops

  • Keep nesting to two or three levels for readability.
  • Use descriptive variable names inside each loop.
  • Break out logic into functions if loops become complex.
  • Consider alternatives like list comprehensions or NumPy for heavy data processing.

Nested loops are a powerful feature in Python programming. They help you solve problems involving grids, combinations, and multi-level data structures. With careful use, they can make your code more elegant and effective.