-3

In the code from below, I wanted to insert some data in a matrix and I was surprised by IndexError. I can't understand why the error is here, it seems that everything is wright.

matrix=[[]]
n=int(input("number of lines and columns n= "))
for i in range(n):
   for j in range(n):
    x=int(input())
    matrix[i].insert(j,x)
    print(i,j)

EDIT:

I understand that my problem had nothing to do with what I thought initially. The mistake was that I wanted to insert x in a list that didn't exist in my matrix variable. The solution is just to append a new list in the first loop, and after that to add desired elements.

Cipri
  • 69
  • 1
  • 8

1 Answers1

1

m is a list of lists Which means that you first need to append a list, and then you can append items to each list.

Just changed your code a bit to do that. Once in every repetition of the outer loop, I append an empty list.

m=[[]]
n=6
for i in range(n):
    m.append([])
    for j in range(n):
        x=5
        m[i].insert(j,x)
        print(i,j)

Try here: https://ideone.com/bSGIiD

That should solve your problem.

Tushar
  • 1,117
  • 1
  • 10
  • 25