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.
Python code
13 linesdef 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
[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
- Use a list comprehension to build each row from the previous row's zip of adjacent pairs
- 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
More from Algorithms & data structures
- Binary Search for Ship Capacity in Python medium
- Binary Search on Answer in Python: Koko Eating Bananas medium
- Bucket Numbers into Histogram Bin Counts in Python easy
- Container With Most Water: Two-Pointer Solution in Python medium
- Count Smaller Elements to the Right in Python easy
- Depth First Search Traversal Order in Python easy
Keep learning
Related tutorials and quizzes for this topic.