Lesson 17 of 60
โฎPrev Nextโฏ

PY-101 ยท Loops

Nested loops

โฑ 8 min ๐Ÿ Real Python 3 ๐ŸŽฌ Animated

17of 60

Your note

My notes for this lesson

Select any text in the lesson to highlight it or add a note. Saved in this browser.

    No highlights yet. Select a sentence in the lesson, then pick a colour or add a note.

    All my bookmarks and notes

    Reading settings

    For every lesson, saved in this browser.

    Text size
    Line spacing
    Font

    With IaaS you rent the virtual machine. Microsoft looks after the building, power and hardware; you patch the operating system.

    โšก The 30-second answer

    A nested loop is a loop inside another loop: for every round of the outer loop, the inner loop runs all the way through. They are how you work with rows and columns, like tables, grids and game boards. If the outer loop runs 3 times and the inner 4, the inner block runs 12 times.

    • Put a loop inside a loop
    • Work out how many times code runs
    • Build rows and columns

    Try it

    Watch it come alive, run it yourself, then prove it. Real Python, right on this page.

    Watch Python run the example. Every variable is a jar; watch the values change and the output appear.

    Nested loops, running
    1. for row in "AB":
    2. line = ""
    3. for seat in range(1, 4):
    4. line = line + f"{row}{seat} "
    5. print(line.strip())
    Press โ–ถ to watch Python run this, one line at a time.
    1. The problemA cinema has 5 rows of 8 seats. To label every seat A1 to E8 you go row by row, and inside each row, seat by seat.
    2. The Python ideafor row in rows:A nested loop is a loop inside another loop: for every round of the outer loop, the inner loop runs all the way through.
    3. In real lifeSpreadsheet tools loop over every row, and inside each row over every column, to find empty cells.

    Start with a question

    A cinema has 5 rows of 8 seats. To label every seat A1 to E8 you go row by row, and inside each row, seat by seat.

    Tables, images (rows of pixels), seating plans and every-pair comparisons all need a loop inside a loop.

    Explain it like I'm 10

    Think of a clock: the minute hand goes all the way round once for every single step of the hour hand.

    The technical explanation

    The inner loop restarts from the beginning on every outer round.

    Use different names for the two loop variables, such as row and col.

    Build each row inside the inner loop, then print it once the row is complete. Or use print(..., end="") to stay on one line and a plain print() to start the next row.

    Syntax

    for row in rows:
        for col in cols:
            ...

    โ–ถ Run the example ๐ŸŽฌ Watch it come alive

    Real-world scenario

    Spreadsheet tools loop over every row, and inside each row over every column, to find empty cells.

    Ready for more?The full lesson adds the technical explanation, interview questions and quick revision.

    Test yourself

    5 questions. Get 4 right and this lesson is marked complete.

    1. 1. Outer loop runs 3 times, inner 5. How many times does the inner block run?
    2. 2. When does the inner loop restart?
    3. 3. What does print("x", end="") do?
    4. 4. Best use of nested loops?
    5. 5. for i in range(2): for j in range(2): print(i, j). First line?

    Questions people ask

    Are nested loops bad in Python?

    No, they are the right tool for grids. They become slow when both loops are large, because the work multiplies.

    How do I break out of two loops at once?

    Put the loops in a function and return, or set a flag variable and check it in the outer loop.

    Interview questions

    How this topic comes up in Python interviews. Answer out loud first, then open the model answer.

    beginner Are nested loops bad in Python?

    No, they are the right tool for grids. They become slow when both loops are large, because the work multiplies.

    beginner How do I break out of two loops at once?

    Put the loops in a function and return, or set a flag variable and check it in the outer loop.

    intermediate Outer loop runs 3 times, inner 5. How many times does the inner block run?

    15. 3 ร— 5 = 15.

    intermediate When does the inner loop restart?

    On every outer round. It runs fully for each outer round.

    Quick revision

    Remember

    • Put a loop inside a loop
    • Work out how many times code runs
    • Build rows and columns
    • Nested loops multiply work. 1,000 outer rounds times 1,000 inner rounds is a million. Keep inner loops small.

    Syntax

    for row in rows:
        for col in cols:
            ...

    Official documentation