1

I'm new to python and I tried to store integer values in a 2 dimensional list using loops(I use this logic in C for getting input for matrix). When I run this code, it shows IndexError: list assignment index out of range. What caused this error? Code to print numbers from 1-9 in matrix form:

num=1
a=[[]]
for i in range(0,3):
    for j in range(0,3):
        a[i][j]=num
        ++num
for i in range(0,3):
    for j in range(0,3):
        print(a[i][j]+" ")
    print("\n")
  • 3
    You create an empty array and then write into it. You need to use append(), or create the array with the initial size. But really look at the "numpy" library – Martin Beckett Jan 12 '18 at 05:20
  • 1
    You have to intialize array indexes first like `a = [[0,0,0]] * 3` or dynamically allocate memory using `append`. – Arunesh Singh Jan 12 '18 at 05:22
  • Also `a = [[3 * r + c for c in range(3)] for r in range(3)]`. Look up list comprehensions. It's a way to create a list with preset values. – Mad Physicist Jan 12 '18 at 05:35

1 Answers1

0

You need to allocate the memory dynamically using append. Also, ++num will not do what you think here and you need num += 1.

num=1
a = []
for i in range(0,3):
    a.append([])
    for j in range(0,3):
        a[i].append(num)
        num += 1

for i in range(0,3):
    for j in range(0,3):
        print(str(a[i][j]) + " ", end="")
    print("\n")

Also, you should look at the numpy library which makes the matrix operations and linear algebra easy, efficient and optimized. The equivalent code in numpy would be:

import numpy as np
mat = np.arange(1,10).reshape(3,3)
print(mat)
Arunesh Singh
  • 3,489
  • 18
  • 26