How to append multi dimensional array using for loop in python

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)

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)

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)]

Tags:

Python

Arrays