Python Pascal's Triangle Generator

Generate and display Pascal's triangle formatted cleanly in the console in Python.

Try Python Pascal's Triangle Generator Code

How it Works

Pascal's triangle is a triangular array of binomial coefficients. The values at the ends of each row are 1, and each intermediate value is the sum of the two values directly above it.

In Python, we build each row list dynamically based on the previous row, appending 1 to the bounds and adding intermediate indices in between.

This provides a great introduction to list indexing, nested arrays, and combinatorics mathematical modeling.

Source Code

Generate Pascal's Triangle rows and format spaces to align the triangle.

pascals_triangle.py
Try in Editor
def generate_pascals_triangle(n):
    triangle = []
    for row_num in range(n):
        row = [1] * (row_num + 1)
        for j in range(1, row_num):
            row[j] = triangle[row_num - 1][j - 1] + triangle[row_num - 1][j]
        triangle.append(row)
    return triangle

# Print the triangle formatted nicely
rows = 5
result = generate_pascals_triangle(rows)
for idx, row in enumerate(result):
    padding = " " * (rows - idx - 1)
    row_str = " ".join(map(str, row))
    print(padding + row_str)
Terminal Output
    1
   1 1
  1 2 1
 1 3 3 1
1 4 6 4 1

Real-world Applications

  • Probability distribution modeling
  • Polynomial expansion calculations math tools
  • Understanding nested list data manipulation structures

Frequently Asked Questions

What is the mathematical definition of a value in Pascal's triangle?

The value at row n and column k is the binomial coefficient C(n, k), representing the number of combinations of choosing k items from n choices.

More Examples