Skip to content
Nested Loops and Patterns
step 1/7

Reading — step 1 of 7

Learn

~3 min readLoops and Iteration

When you put one loop inside another, the inner loop runs completely for every single step of the outer loop. If the outer runs 5 times and the inner runs 3 times, the innermost code runs 5 × 3 = 15 times. It's multiplication, not addition. This unlocks grids, tables, two-dimensional patterns — and almost every brute-force algorithm you'll ever write.

The mental model

python

Output:

0 0
0 1
0 2
0 3
1 0
1 1
...
2 3

12 lines total — 3 outer iterations × 4 inner each.

Walking a grid

Most two-dimensional data is naturally a list of lists. Walk it with two for loops:

python

Output:

1 2 3 
4 5 6 
7 8 9 

String repetition shortcut

Python lets you multiply strings:

python

This often replaces an inner loop entirely:

python

Building a triangle (canonical exercise)

python

Output:

*
**
***
****
*****

For right-alignment, pad with spaces:

python

Multiplication table

python

Output:

   1   2   3   4   5
   2   4   6   8  10
   3   6   9  12  15
   4   8  12  16  20
   5  10  15  20  25

Performance — nested loops compound

A loop of 1000 iterations is fast. A loop of 1000 inside a loop of 1000 is a million iterations. A triple nested loop of 1000 each is a billion. This is the hidden cost of nesting.

Algorithm complexity in CS terms: a single loop is O(n), a doubly-nested loop is O(n²). For n = 100k, O(n²) is 10 billion operations — minutes of compute. Whenever a nested loop seems slow, ask: "can I do this with one pass and a dictionary?"

Common mistakes

  • Reusing the same loop variable: for i in range(3): for i in range(4): works but is confusing. Use distinct names like row/col, i/j.
  • Indentation depth: 3-deep nested loops indent 12 spaces in. If you're at 16+ spaces, refactor — extract a function.
  • Off-by-one in pyramids: forgetting the + 1 in range(1, height + 1) cuts off the top row.
  • Forgetting the inner print() after the inner loop ends — your grid prints all on one line.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…