Home › Learn › Python › Loops

Nested loops

Lesson 14 of 40. A loop inside a loop covers every combination.

Putting one loop inside another runs the inner loop completely for every round of the outer loop. Two loops over ten items each give a hundred rounds. That is how you visit every cell of a grid or every pair of items.

Build grids as a list of rows: create an empty row list in the outer loop, fill it in the inner loop, then append the row to the result. To pair items without repeats, let the inner index start one past the outer index.

for row in range(2):
    for col in range(3):
        print(row, col)
# (0,0) (0,1) (0,2) (1,0) (1,1) (1,2)

Your task

Write multiplication_table(n) returning a list of n rows, where row i holds i * 1 up to i * n, so multiplication_table(3) is [[1, 2, 3], [2, 4, 6], [3, 6, 9]]. Then write pairs(items) returning every pair of items as tuples, each pair once, in order: pairs(["a", "b", "c"]) is [("a", "b"), ("a", "c"), ("b", "c")].

Hint 1

for i in range(1, n + 1): row = []; for j in range(1, n + 1): row.append(i * j); rows.append(row)

Hint 2

for i in range(len(items)): for j in range(i + 1, len(items)): result.append((items[i], items[j]))

Show the solution
def multiplication_table(n):
    rows = []
    for i in range(1, n + 1):
        row = []
        for j in range(1, n + 1):
            row.append(i * j)
        rows.append(row)
    return rows


def pairs(items):
    result = []
    for i in range(len(items)):
        for j in range(i + 1, len(items)):
            result.append((items[i], items[j]))
    return result

    Runs CPython compiled to WebAssembly in this tab (12 MB download the first time, then cached); nothing is sent anywhere.