Nested Loops

Nested Loops

A loop body can contain another loop. The inner loop runs completely for every pass of the outer loop:

for row in range(1, 3):
    for column in range(1, 4):
        print(f"row {row}, column {column}")

Output:

row 1, column 1
row 1, column 2
row 1, column 3
row 2, column 1
row 2, column 2
row 2, column 3

The outer loop made 2 passes; each pass ran the inner loop 3 times — 6 lines in total. Every combination of the two loop variables appears exactly once.

Nested loops pair with the list-building pattern: one result list before both loops, one append in the innermost body.

Exercise

  1. Define a function named all_tables with two parameters, sizes (a list of table sizes, e.g. ["S", "M"]) and colors (a list of color names).
  2. It returns a list of strings, one per size-color combination, in the form <size>-<color>. Sizes vary in the outer loop, colors in the inner.

all_tables(["S", "M"], ["oak", "pine"]) returns ["S-oak", "S-pine", "M-oak", "M-pine"].

Run your code to see the output, then press Submit.

Tests

import unittest


class TestAllTables(unittest.TestCase):
    def test_two_by_two(self):
        self.assertEqual(
            all_tables(["S", "M"], ["oak", "pine"]),
            ["S-oak", "S-pine", "M-oak", "M-pine"],
        )

    def test_one_size_three_colors(self):
        self.assertEqual(
            all_tables(["L"], ["red", "green", "blue"]),
            ["L-red", "L-green", "L-blue"],
        )

    def test_empty_colors_gives_empty_list(self):
        self.assertEqual(all_tables(["S", "M"], []), [])
def all_tables(sizes, colors):
    result = []
    for size in sizes:
        for color in colors:
            result.append(f"{size}-{color}")
    return result


print(all_tables(["S", "M"], ["oak", "pine"]))
Solution hidden. Give it a real try first.

Sign in to join the discussion.

No comments yet. Be the first to ask a question.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.