Python programs / Patterns / Pascal's triangle

Python Program to Print Pascal's Triangle

Beginner Patterns

Prints Pascal's triangle, working out each row from the one above it: every number inside a row is the sum of the two above it.

Pascal's triangle starts with a 1 at the top. Every row begins and ends with 1, and each number in between is the sum of the two numbers above it. From the row 1 3 3 1, the next is 1, then 1 + 3, 3 + 3 and 3 + 1, then 1: 1 4 6 4 1. These numbers turn up all over maths: they're the coefficients of (a + b)⁴ = a⁴ + 4a³b + 6a²b² + 4ab³ + b⁴, and the number of ways to choose 0, 1, 2, 3 or 4 things from 4.

Program

def pascals_triangle(n):
    """Print the first n rows of Pascal's triangle."""
    row = [1]
    for i in range(n):
        # 4 characters per number; each row starts 2 further left
        line = " " * 2 * (n - 1 - i)
        for number in row:
            line += f"{number:4}"
        print(line)

        # The next row: 1, each pair of neighbours added, then 1
        next_row = [1]
        for k in range(1, len(row)):
            next_row.append(row[k - 1] + row[k])
        next_row.append(1)
        row = next_row


pascals_triangle(6)

Open in the editor Download pascals_triangle.py

Output

             1
           1   1
         1   2   1
       1   3   3   1
     1   4   6   4   1
   1   5  10  10   5   1

How it works

  1. row holds the numbers of the row about to be printed. The triangle starts with a single 1.
  2. The loop runs once per row, n times, with i counting the rows from 0.
  3. The printed line starts with 2 spaces for each row still to come below this one: 2 * (n - 1 - i). The bottom row has none.
  4. Each number is added 4 characters wide: f"{number:4}" puts spaces in front of it to fill them, 3 for 1 and 2 for 10 (string formatting). Then the line is printed.
  5. The next row starts with 1. The loop adds up each pair of neighbours in row, row[k - 1] + row[k], and the row ends with another 1. From [1, 3, 3, 1], the pairs give 4, 6 and 4, so the next row is [1, 4, 6, 4, 1].
  6. row becomes the new row, ready for the next time round the loop.
  7. The program prints 6 rows. The 6th has the first numbers with two digits, 10 and 10.

For n = 6:

i Spaces: 2 * (n - 1 - i) row
0 10 [1]
1 8 [1, 1]
2 6 [1, 2, 1]
3 4 [1, 3, 3, 1]
4 2 [1, 4, 6, 4, 1]
5 0 [1, 5, 10, 10, 5, 1]

Why 2 and 4: every number takes 4 characters, and each row starts 2 characters, half a number, further left than the row above. So each number sits halfway between the two numbers above it, the two that add up to it, and the rows make a triangle.

Other ways to write it

With math.comb()

Each number can also be worked out on its own. The number at place k in row i, both counting from 0, is comb(i, k): the number of ways to choose k things from i.

from math import comb

def pascals_triangle(n):
    for i in range(n):
        row = [comb(i, k) for k in range(i + 1)]
        cells = "".join(f"{number:4}" for number in row)
        print(" " * 2 * (n - 1 - i) + cells)

pascals_triangle(5)

With zip()

zip(row, row[1:]) pairs each number with the one after it, so a list comprehension can make the next row in one line.

def pascals_triangle(n):
    row = [1]
    for i in range(n):
        cells = "".join(f"{number:4}" for number in row)
        print(" " * 2 * (n - 1 - i) + cells)
        row = [1] + [a + b for a, b in zip(row, row[1:])] + [1]

pascals_triangle(5)

Try it yourself

  • Print 10 rows: the numbers reach 126, and with 4 characters each they still line up.
  • Print each row's total next to it. The totals are the powers of 2: 1, 2, 4, 8, 16, 32.
  • Print row itself in place of the spaced line, to see each row as a list.
  • Print 14 rows. The last one holds 1716, which fills all 4 characters with no space before it. Make each number 6 characters wide and the indent 3 spaces per row to fix it.

More patterns programs

Share this program