0Pricing
Python Academy · Lesson

Nested Loops and Loop Patterns

Combine nested loops for grids, patterns, and accumulation.

Nested Loops and Loop Patterns is a free Python Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Python Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Introduction

Combining loops unlocks patterns like matrix traversal, multi-level search, and generating combinations.

Basic Nested Loop

Two for loops: the outer runs N times, the inner runs M times per outer iteration — total N*M iterations.
for i in range(3):
    for j in range(3):
        print(i, j)

Multiplication Table

Nested loops naturally produce tables. The outer loop is the row, inner is the column.
for i in range(1, 4):
    for j in range(1, 4):
        print(f'{i*j:3}', end='')
    print()

Triangle Pattern

Print * i times per row: for i in range(1,6): print('*'*i). Demonstrates how inner count depends on outer.
for i in range(1, 6):
    print('*' * i)

Matrix Traversal

Nested loops are the canonical way to visit every cell of a 2D list.
matrix = [[1,2,3],[4,5,6]]
for row in matrix:
    for val in row:
        print(val, end=' ')
    print()

Accumulation Pattern

Sum all elements: total = 0; for row in matrix: for v in row: total += v
matrix = [[1,2],[3,4]]
total = sum(v for row in matrix for v in row)
print(total)

Finding Elements

Search for a value in a 2D list and record its position with a nested loop.
matrix = [[1,2,3],[4,5,6],[7,8,9]]
for i, row in enumerate(matrix):
    for j, val in enumerate(row):
        if val == 5:
            print(f'Found at ({i},{j})')

Combinations Without repetition

for i in range(n): for j in range(i+1, n): generates all unique pairs from a list.
items = ['a','b','c']
for i in range(len(items)):
    for j in range(i+1, len(items)):
        print(items[i], items[j])

Nested Loop Efficiency

O(n^2) is common for nested loops. If the inner loop does a dict lookup instead of a list scan, you can reduce to O(n).
# Efficient: use a set for inner lookup
data = {1, 2, 3, 4}
result = [x for x in range(10) if x in data]  # O(n)
print(result)

Flattening with Nested Comprehension

[x for row in matrix for x in row] is a flat nested comprehension. Read it left to right: outer loop first.
matrix = [[1,2],[3,4]]
flat = [x for row in matrix for x in row]
print(flat)

Breaking Out of Nested Loops

Use a flag or put loops in a function and return to exit multiple levels cleanly.
def find_in_matrix(matrix, target):
    for i, row in enumerate(matrix):
        for j, val in enumerate(row):
            if val == target:
                return (i, j)
    return None
print(find_in_matrix([[1,2],[3,4]], 3))

Quick Check

What is the total number of iterations for two nested loops with range(4) and range(3)?

Recap

Nested loops: N*M total iterations. Use for patterns, matrix traversal, and combinations. Flatten with comprehension. Break out with return or a flag.

Keep Going

Great work! Move on to the next lesson to continue building your skills.

Frequently asked questions

Is the “Nested Loops and Loop Patterns” lesson free?

Yes — the full text of “Nested Loops and Loop Patterns” is free to read here on the web, and the Python Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Python Academy course, upgrade to CoddyKit PRO.

What will I learn in “Nested Loops and Loop Patterns”?

Combine nested loops for grids, patterns, and accumulation. You practise Python Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Python Academy?

No prior experience is required. Python Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Nested Loops and Loop Patterns” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Python Academy lesson?

Yes. Every Python Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. if / elif / else Statements
  2. for Loops and range()
  3. while Loops and Loop Control
  4. Nested Loops and Loop Patterns
← Back to Python Academy