Module 3 · Beginner · Conditions and loops

Nested loops and star patterns in Python

Nested loops in Python with star pattern programs: right triangles, pyramids, number patterns and tables, how to plan any pattern, and the cost of nested loops.

By theprogrammers team · · 9 min read

A cinema hall has 10 rows and 12 seats in each row. To check every seat, you walk along row 1 seat by seat, then row 2, and so on. That's a nested loop: one loop (the seats) running inside another (the rows). Nested loops in Python handle anything with rows and columns, such as tables, grids, spreadsheets, images and game boards.

Star pattern programs are the classic way to practise them. They show up in almost every college lab and in many first-round coding tests in India. They look like puzzles, but each one follows the same short plan, which this lesson shows you.

What you need first: Python for and while loops and break, continue and pass.

Key terms

  • Nested loop: a loop written inside the body of another loop.
  • Outer loop: the loop on the outside. In patterns it usually controls the rows.
  • Inner loop: the loop on the inside. It runs completely, from start to finish, on every pass of the outer loop.
  • Row and column: a row goes across, a column goes down. Row i and column j name one cell, like a seat number.
  • end argument: print("*", end="") prints without moving to a new line, so the next print stays on the same line.

How nested loops work in Python

Here's a small hall with 3 rows and 4 seats per row:

for row in range(1, 4):
    for seat in range(1, 5):
        print(f"R{row}S{seat}", end=" ")
    print()     # move to the next line after each row
R1S1 R1S2 R1S3 R1S4
R2S1 R2S2 R2S3 R2S4
R3S1 R3S2 R3S3 R3S4

Follow it in order:

  1. The outer loop sets row = 1.
  2. The inner loop runs fully: seats 1, 2, 3, 4 are printed on one line.
  3. The empty print() ends the line.
  4. The outer loop moves on to row = 2, and the inner loop starts again from seat 1.

The inner loop ran 4 times for each of the 3 rows, so the inner body ran 3 × 4 = 12 times in total.

A multiplication table

The same shape builds a table. Each cell is row × column:

for i in range(1, 6):
    for j in range(1, 6):
        print(f"{i * j:4}", end="")
    print()
   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

{i * j:4} prints each number in a space 4 characters wide, so the columns line up. Python f-strings covers this width trick.

How to plan any star pattern

Don't stare at the picture. Fill in a small table instead:

  1. Count the rows. That's your outer loop.
  2. For each row, count the spaces and the stars. Write the numbers down for rows 1, 2 and 3.
  3. Find the rule that turns the row number into those counts.
  4. Write the inner part, often just " " * spaces + "*" * stars.

Python can multiply a string: "*" * 3 is "***". That means you often need only one loop, plus string multiplication. Below, each pattern shows the nested-loop version first, so you understand it, and then the shorter version.

Pattern 1: right-angled triangle

Row iStars
11
22
33

The rule is "row i has i stars":

n = 5
for i in range(1, n + 1):
    for j in range(i):
        print("*", end="")
    print()
*
**
***
****
*****

The same thing with string multiplication:

n = 5
for i in range(1, n + 1):
    print("*" * i)
*
**
***
****
*****

Pattern 2: inverted triangle

Now the counts go down: 5, 4, 3, 2, 1. Count the outer loop backwards with a step of −1:

n = 5
for i in range(n, 0, -1):
    print("*" * i)
*****
****
***
**
*

Pattern 3: right-aligned triangle

The stars are pushed to the right, so each row starts with spaces.

Row i (n = 5)SpacesStars
141
232
323

Spaces plus stars always add up to 5, so spaces = n − i (read "n minus i"):

n = 5
for i in range(1, n + 1):
    print(" " * (n - i) + "*" * i)
    *
   **
  ***
 ****
*****

Pattern 4: pyramid

This one takes most people a few tries. Look at the star counts: 1, 3, 5, 7, 9. They go up by 2 each row.

Row i (n = 5)SpacesStars
141
233
325
417

The rule for stars is 2*i* − 1 ("two i minus one"): row 3 gives 2 × 3 − 1 = 5. Spaces are still n − i.

n = 5
for i in range(1, n + 1):
    print(" " * (n - i) + "*" * (2 * i - 1))
    *
   ***
  *****
 *******
*********

Here's the same pyramid with two inner loops, the way many lab manuals write it:

n = 5
for i in range(1, n + 1):
    for s in range(n - i):
        print(" ", end="")
    for k in range(2 * i - 1):
        print("*", end="")
    print()
    *
   ***
  *****
 *******
*********

Pattern 5: diamond

A diamond is a pyramid followed by an upside-down pyramid. The second half starts one row short, so the widest row isn't printed twice:

n = 4
for i in range(1, n + 1):
    print(" " * (n - i) + "*" * (2 * i - 1))
for i in range(n - 1, 0, -1):
    print(" " * (n - i) + "*" * (2 * i - 1))
   *
  ***
 *****
*******
 *****
  ***
   *

Number patterns

Swap the star for a number. Here the inner loop prints its own counter j:

n = 5
for i in range(1, n + 1):
    for j in range(1, i + 1):
        print(j, end=" ")
    print()
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

And Floyd's triangle, where the numbers keep counting across rows. A separate variable carries on between rows:

number = 1
for i in range(1, 5):
    for j in range(i):
        print(number, end=" ")
        number += 1
    print()
1
2 3
4 5 6
7 8 9 10

Common mistakes

  • Forgetting the empty print() after the inner loop. Everything comes out on one long line.
  • Putting the empty print() inside the inner loop. You get one star per line.
  • Off-by-one errors. range(1, n) stops at n − 1, so you get one row too few. Use range(1, n + 1).
  • Reusing the same variable name for both loops, like for i ... inside for i .... The inner loop overwrites the outer one's value.
  • Trailing spaces. print(j, end=" ") leaves a space at the end of each row. It's invisible on screen, but some online judges compare output exactly. Build the row as a string and use " ".join(...) when that matters.

How much work nested loops do

Two loops over n items do n × n = n² steps ("n squared"). That's fine for a 5-row pattern. For 1 lakh items it's 10 billion steps, which can take minutes.

for n in [10, 100, 1000]:
    steps = 0
    for i in range(n):
        for j in range(n):
            steps += 1
    print(n, steps)
10 100
100 10000
1000 1000000

Ten times more items means a hundred times more work. This is why nested loops are the first thing to check when code is slow; Big-O notation explains how to measure it. In data science, libraries like NumPy and pandas replace many nested loops with fast whole-array operations.

Where nested loops are used

  • Grids and images: an image is rows and columns of pixels.
  • Tables and spreadsheets: rows of records, each with several columns.
  • Comparing every pair: finding duplicate entries or the two closest cities.
  • Matrices: matrix multiplication, a core step in machine learning, is three nested loops.

Practice

  1. Print a 4 × 6 rectangle of # characters.
Show the answer
for row in range(4):
    print("#" * 6)
######
######
######
######

One loop is enough, because every row is the same.

  1. Print this pattern for n = 4:
1
22
333
4444
Show the answer

Row i prints the digit i, i times. Turn the number into a string so it can be repeated:

n = 4
for i in range(1, n + 1):
    print(str(i) * i)
1
22
333
4444
  1. Print an inverted pyramid of height 4 (7 stars on top, 1 at the bottom).
Show the answer

Run the pyramid rule with the row number counting down. Spaces are n − i and stars are 2*i* − 1:

n = 4
for i in range(n, 0, -1):
    print(" " * (n - i) + "*" * (2 * i - 1))
*******
 *****
  ***
   *
  1. Print the multiplication tables of 2 to 4 side by side, for 1 to 5, using a nested loop.
Show the answer

The outer loop is the multiplier (rows), the inner loop is the table (columns):

for k in range(1, 6):
    for table in range(2, 5):
        print(f"{table} x {k} = {table * k:2}", end="    ")
    print()
2 x 1 =  2    3 x 1 =  3    4 x 1 =  4
2 x 2 =  4    3 x 2 =  6    4 x 2 =  8
2 x 3 =  6    3 x 3 =  9    4 x 3 = 12
2 x 4 =  8    3 x 4 = 12    4 x 4 = 16
2 x 5 = 10    3 x 5 = 15    4 x 5 = 20
  1. Write a nested loop that prints every pair of different students from ["Ahana", "Rohan", "Meera"], each pair once (so Ahana-Rohan but not also Rohan-Ahana).
Show the answer

Start the inner loop one position after the outer one, so no pair is repeated and nobody is paired with themselves:

students = ["Ahana", "Rohan", "Meera"]
for i in range(len(students)):
    for j in range(i + 1, len(students)):
        print(students[i], "-", students[j])
Ahana - Rohan
Ahana - Meera
Rohan - Meera

For n students this gives n(n − 1) ÷ 2 pairs: 3 × 2 ÷ 2 = 3.

Interview questions

How many times does the inner body run in two nested loops of sizes m and n?

m × n times. For two loops over the same n items that's n², so the time complexity is O(n²).

How would you print a pyramid of n rows?

Row i needs n − i spaces and 2*i* − 1 stars: for i in range(1, n + 1): print(" " * (n - i) + "*" * (2 * i - 1)).

How can you make nested loops faster?

Avoid them when a better tool exists: a set or dictionary for lookups (one loop instead of two), built-in functions, or NumPy operations on whole arrays. When you must compare pairs, start the inner loop at i + 1 to halve the work.

Key takeaways

  • The inner loop runs completely on every pass of the outer loop.
  • In patterns, the outer loop is the rows; the inner loop or string multiplication builds each row.
  • Plan a pattern with a table of row number, spaces and stars, then find the rule.
  • The pyramid rule: n − i spaces and 2*i* − 1 stars.
  • Two nested loops over n items do n² steps, which gets slow fast.

Frequently asked questions

Why are pattern programs asked in exams and tests?

They check that you understand how nested loops run, in what order, and how to turn a picture into a rule. The planning skill transfers directly to real problems with rows and columns.

How many levels of nesting are too many?

Two levels are common. Three is sometimes needed, as in matrix multiplication. Beyond that, the code gets hard to follow, so move the inner part into a function.

Can a while loop be nested inside a for loop?

Yes. Any loop can go inside any other loop, and break and continue always apply to the innermost loop they're in.

What to learn next

  1. Handle fixed choices with the Python match statement.
  2. Test yourself with Python loop practice: 20 problems.
  3. Learn to measure how slow nested loops are with Big-O notation.