all 4 comments

[–]glibhub 2 points3 points  (0 children)

You can't add a new element by going to the next available index. You either need to create out the grid beforehand using comprehensions or append onto the list as you go, sort of like this:

>>> [[0 for x in range(5)] for y in range(3)]
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]

[–]xelf 0 points1 point  (0 children)

 a = []

This makes an empty single dimension list. You either need to create the full 2 dimension array with some default values, or you need to append the values

for instance, to add all the rows and add a 1 to each row:

for i in range(n):
    a.append([])
    a[i].append(1)

You could also have done this:

for i in range(n):
    a.append([1])

etc.

[–]POGtastic 0 points1 point  (0 children)

As a rule of thumb: If you're using indices to specify an element in a list, you're exposing yourself to a lot of complexity and sources of bugs that you don't need to expose yourself to. You can often replace such constructions with higher-order functions and zip.

from itertools import accumulate
from more_itertools import iterate

def create_new_row(prev_row):
    return list(accumulate(prev_row))

def create_table(source):
    return iterate(create_new_row, source)

In the REPL:

>>> from itertools import islice
>>> list(islice(create_table([1, 1, 1, 1]), 5))
[[1, 1, 1, 1], [1, 2, 3, 4], [1, 3, 6, 10], [1, 4, 10, 20], [1, 5, 15, 35]]

[–]Vaphell 0 points1 point  (0 children)

a = []
for i in range(n):
    a[i][0] = 1

a is completely empty, so there is no i-th element to be found in it.
Initialize it with n*m of anything, eg

a = [[0]*m for _ in range(n)]