Python Program to Print Pascal Triangle
row[i] = row[i] + row[i-1] inside a loop; for example, use for i in range(n): row = [1] + [row[j] + row[j+1] for j in range(len(row)-1)] + [1] to generate each row.Examples
How to Think About It
Algorithm
Code
def print_pascals_triangle(n): row = [] for i in range(n): row = [1] + [row[j] + row[j+1] for j in range(len(row)-1)] + [1] if row else [1] print(' '.join(map(str, row))) print_pascals_triangle(5)
Dry Run
Let's trace printing 5 rows of Pascal's Triangle through the code
Start with empty row
row = []
First iteration (i=0)
row is empty, so row = [1] Print: 1
Second iteration (i=1)
row = [1] + [] + [1] = [1, 1] Print: 1 1
Third iteration (i=2)
row = [1] + [1+1] + [1] = [1, 2, 1] Print: 1 2 1
Fourth iteration (i=3)
row = [1] + [1+2, 2+1] + [1] = [1, 3, 3, 1] Print: 1 3 3 1
Fifth iteration (i=4)
row = [1] + [1+3, 3+3, 3+1] + [1] = [1, 4, 6, 4, 1] Print: 1 4 6 4 1
| Iteration | Row Values |
|---|---|
| 0 | [1] |
| 1 | [1, 1] |
| 2 | [1, 2, 1] |
| 3 | [1, 3, 3, 1] |
| 4 | [1, 4, 6, 4, 1] |
Why This Works
Step 1: Initialize first row
The first row of Pascal's Triangle is always [1], which starts the pattern.
Step 2: Build next rows
Each new row is created by adding pairs of adjacent numbers from the previous row, with 1 added at the start and end.
Step 3: Print rows
Print each row as a space-separated string to display the triangle shape.
Alternative Approaches
from math import factorial def print_pascals_triangle(n): for i in range(n): row = [str(factorial(i)//(factorial(j)*factorial(i-j))) for j in range(i+1)] print(' '.join(row)) print_pascals_triangle(5)
def pascal_row(n): if n == 0: return [1] prev = pascal_row(n-1) return [1] + [prev[i] + prev[i+1] for i in range(len(prev)-1)] + [1] def print_pascals_triangle(n): for i in range(n): print(' '.join(map(str, pascal_row(i)))) print_pascals_triangle(5)
Complexity: O(n^2) time, O(n) space
Time Complexity
The program prints n rows, each with up to n elements, so it runs in O(n^2) time due to nested loops.
Space Complexity
Each row stores up to n elements, so space complexity is O(n). The program reuses the row list each iteration.
Which Approach is Fastest?
The iterative approach with list comprehension is fastest and simplest; factorial-based methods are slower due to expensive calculations.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Iterative with list comprehension | O(n^2) | O(n) | Most efficient and readable |
| Factorial formula | O(n^3) | O(1) | Mathematical clarity but slower |
| Recursive | O(n^2) | O(n^2) | Conceptual clarity but uses more memory |