Generate Pascal's Triangle Rows in Python

Builds Pascal's triangle as a list of rows, where each inner value is the sum of the two values above it.

Easy Python 3.9+ Aug 9, 2026 Algorithms & data structures 14 views 0 copies

Python code

13 lines
Python 3.9+
def generate_pascals_triangle(rows):
    triangle = []
    for row_num in range(rows):
        row = [1] * (row_num + 1)
        for col in range(1, row_num):
            row[col] = triangle[row_num - 1][col - 1] + triangle[row_num - 1][col]
        triangle.append(row)
    return triangle

if __name__ == "__main__":
    result = generate_pascals_triangle(5)
    for row in result:
        print(row)

Output

stdout
[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]

How it works

The code initializes each row with 1s, which handles the edges correctly since the first and last elements of any row are always 1. For inner positions (columns 1 through row_num-1), it computes each value as the sum of the two numbers directly above from the previous row. The triangle list accumulates rows progressively, and each new row references the previous row's indices to build itself. This runs in O(n²) time because it visits each element once, which is optimal for producing all n rows of Pascal's triangle.

Common mistakes

  • Off-by-one errors in row size when creating `[1] * (row_num + 1)`
  • Forgetting the inner loop range should exclude both ends (range(1, row_num))
  • Accessing `triangle[row_num - 1]` before appending the current row
  • Indexing the previous row incorrectly with col vs col-1

Variations

  1. Use a list comprehension to build each row from the previous row's zip of adjacent pairs
  2. Generate only a single row using math.comb (combinations) to avoid building the full triangle

Real-world use cases

  • Computing binomial coefficients for probability calculations in statistical experiments.
  • Generating polynomial expansion coefficients for algebra or signal-processing code.
  • Creating visual number patterns for educational tools or coding challenges in UIs.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Algorithms & data structures

Related tutorials and quizzes for this topic.