Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Generate Pascal's Triangle

Produce the first n rows of Pascal's triangle using loops.

Python practice24 minLoops & IterationAdvancedLast updated March 15, 2026

Problem statement

Write pascals_triangle(n) that returns a list of lists representing the first n rows (top to bottom) of Pascal's triangle. Each row is a list of integers. Rules: - Row 1 is [1]. - Each element inside a row (not on edges) is the sum of the two elements above it from the previous row. - If n is 0, return an empty list. Use loops to build rows iteratively. Aim for clarity and correctness for n up to at least 20.

Task

Implement a function to generate Pascal's triangle rows iteratively without using recursion or external libraries.

Examples

First 5 rows

Input

pascals_triangle(5)

Output

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

Each row is built from the previous row by summing adjacent pairs and adding 1s at the ends.

Input format

A single integer n (number of rows).

Output format

A list of n lists, each inner list is a row of integers from Pascal's triangle.

Constraints

0 <= n <= 20. Time complexity O(n^2) is acceptable. Use loops (for/while) to build the triangle.

Samples

Sample 1

Input

pascals_triangle(3)

Output

[[1], [1, 1], [1, 2, 1]]

Three rows starting from [1].