Max Monteil
Max Monteil

Reputation: 13

Why is this pascal triangle function not giving a list index error?

I've been doing an assignment for uni that requires us to generate Pascal triangles in python. My code works but I don't understand why as I was expecting to get a List Index error for line 8 (and the ones after too).

Here is the function itself, it would be great if someone could explain what happens.

def generate_pascal(n):
    pascal = []

    for i in range(n + 1):  # columns
        row = []
        row.append(1)  # first item is always 1
        for j in range(i):  # rows
            # The pascal list is empty shouldn't I be getting an index error?
            last = len(pascal) - 1
            row.append(pascal[last][j + 1] + pascal[last][j])
        row.append(0)  # To be able to add the last item to its adjacent number
        pascal.append(row)

    return pascal

Upvotes: 0

Views: 68

Answers (1)

Ken Wei
Ken Wei

Reputation: 3130

In your first iteration, i is equal to 0. range(0) is empty, so that for loop doesn't run, and your pascal list is immediately appended to without running the for loop in j.

Upvotes: 3

Related Questions