Python programs / Patterns / Diamond pattern

Python Program to Print a Diamond Pattern

Beginner Patterns

Prints a diamond of stars: the rows of a pyramid going down to the widest one, then the same rows again in reverse.

A diamond is a pyramid with an upside-down copy of itself underneath. With 5 rows to the middle, the top half has 1, 3, 5, 7 and 9 stars and the bottom half 7, 5, 3 and 1. The widest row is printed only once, so the diamond is 9 lines tall. Every line is worked out the same way as a pyramid's row, from its row number.

Program

def diamond(n):
    """Print a diamond of stars, 2 * n - 1 rows tall."""
    # Rows 1 to n of a pyramid, then rows n - 1 back down to 1
    rows = list(range(1, n + 1)) + list(range(n - 1, 0, -1))
    for row in rows:
        spaces = n - row
        stars = 2 * row - 1
        print(" " * spaces + "*" * stars)


diamond(5)

Open in the editor Download diamond.py

Output

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

How it works

  1. rows lists which pyramid row each line of the diamond copies: 1 up to n, then n - 1 back down to 1. range(n - 1, 0, -1) counts backwards, as its third number, the step, is -1, and it stops before 0 (for loops). For n = 5, rows is [1, 2, 3, 4, 5, 4, 3, 2, 1].
  2. The loop prints one line for each number in rows.
  3. As in a pyramid, row row has n - row spaces in front and 2 * row - 1 stars: the further down the pyramid, the fewer spaces and the more stars.
  4. The spaces and then the stars make one string, printed as the line.
  5. The program prints a diamond 5 rows to the middle, 9 lines in all.

For n = 5:

Line printed row Spaces: n - row Stars: 2 * row - 1
1 1 4 1
2 2 3 3
3 3 2 5
4 4 1 7
5 5 0 9
6 4 1 7
7 3 2 5
8 2 3 3
9 1 4 1

The middle star of every line lands in the 5th column, so the two halves line up.

Other ways to write it

With two loops

The version most courses show: one loop prints the top half, and a second, counting down, the bottom half.

def diamond(n):
    for row in range(1, n + 1):
        print(" " * (n - row) + "*" * (2 * row - 1))
    for row in range(n - 1, 0, -1):
        print(" " * (n - row) + "*" * (2 * row - 1))

diamond(3)

With abs()

One loop can count i from 1 - n to n - 1. abs(i) drops the minus sign, so n - abs(i) goes up to n and back down: 1, 2, 3, 2, 1 for n = 3.

def diamond(n):
    for i in range(1 - n, n):
        row = n - abs(i)
        print(" " * (n - row) + "*" * (2 * row - 1))

diamond(3)

Try it yourself

  • Print diamond(3) and diamond(7). A diamond n rows to the middle is 2 * n - 1 lines tall: 13 for 7.
  • Swap the two halves of rows to make an hourglass: list(range(n, 0, -1)) + list(range(2, n + 1)).
  • Space the stars out: print n - row spaces, then "* " * row.
  • Make it hollow, with a star only at each end of a line: a row wider than one star prints "*" + " " * (stars - 2) + "*".

More patterns programs

Share this program