5

I am trying to append to a multi-dimensional array.

This is what I have done so far:

arr=[[]]
for i in range(10):
    for j in range(5):
        arr[i].append(i*j)
        print i,i*j


print arr

This is my expected output:

[[0,0,0,0,0],[0,1,2,3,4],[0,2,4,6,8],[0,3,6,9,12],[0,4,8,12,16],[0,5,10,15,20],[0,6,12,18,24],[0,7,14,21,28],[0,8,16,24,32],[0,9,18,27,36]]

However, I am getting this error:

IndexError: list index out of range

gyre
  • 16,369
  • 3
  • 37
  • 47
Eka
  • 14,170
  • 38
  • 128
  • 212

4 Answers4

8

You're forgetting to append the empty list beforehand. Thus why you get a, IndexError when you try to do arr[i].

arr = []
for i in range(10):
    arr.append([])
    for j in range(5):
        arr[i].append(i*j)
vallentin
  • 23,478
  • 6
  • 59
  • 81
7

You need to define your initial array in the following way: arr=[[] for i in range(10)], as you cannot append a value to a nonexistent array (which is what happens when i>=1). So the code should look like:

arr=[[] for i in range(10)]
for i in range(10):
    for j in range(5):
        arr[i].append(i*j)
        print(i,i*j)


print(arr)
Miriam Farber
  • 18,986
  • 14
  • 61
  • 76
2

As others have pointed out, you need to make sure your list of lists is initially populated with ten empty lists (as opposed to just one) in order for successive elements to be appended correctly.

However, I might suggest using a terser nested list comprehension instead, which avoids the problem entirely by creating the list in a single statement:

arr = [[i*j for j in range(5)] for i in range(10)]
Community
  • 1
  • 1
gyre
  • 16,369
  • 3
  • 37
  • 47
0

You init your arr as an array with only 1 element, so you have such an error when i goes greater than 0. You can use list comprehensive to archive your purpose:

[[i * j for j in range(5)] for i in range(10)]
shizhz
  • 11,715
  • 3
  • 39
  • 49