0

I get this error:

Traceback (most recent call last): File "C:/Python27/main.py", line 21, in matrix[1][1].append(2) IndexError: list index out of range

This is my code

file = open("C:\\Python27\\test.txt", "r")

s1 = file.read();
s2 = file.read();

matrix = [[0 for x in range(len(s1))] for x in range(len(s2))]

matrix[1][1].append(2)
print matrix[1][1]

len(s1) and len(s2) is larger than 5

I try using matrix[1][1] = 2 instead of matrix[1][1].append(2)but it won't work.

So what's my mistakes?

4
  • 3
    just for the record: You are not asking any question. Commented Jul 29, 2015 at 14:03
  • matrix[1][1].append(2) will certainly not work as you are trying to append to an int Commented Jul 29, 2015 at 14:11
  • also you might want to test len(s2) again. Commented Jul 29, 2015 at 14:13
  • Just a comment on style, I'd use matrix = [ [0] * len(s1) ] * len(s2) Commented Nov 2, 2016 at 17:01

1 Answer 1

3

I'd print len(s1) and len(s2). They are probably not what you expect. And if you want to set row 1 col 1 of matrix you would do:

matrix[1][1] = 2

because otherwise you are trying to append number 2 to element at (1,1) which is not a list.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.