cbbcbail
cbbcbail

Reputation: 1771

Python Matrix: Value not in list error

I am writing a Python program that creates a 9x9 matrix with all of the values being 0. Then I have to manually put in the a actual values I want to be in it. (That is why I have all of the inserts.) I am trying to use the list.remove(x) command with list being the matrix and x being the value I am trying to remove. I know that the x value I am putting in is in the matrix but I keep getting an error saying it isn't.

Here is my code:

matrix = [[0 for x in range (9)] for y in range (9)]
C = matrix.count([0, 0, 0, 0, 0, 0, 0, 0, 0])
matrix.insert(0, [0, 0, 0, 5, 0, 0, 0, 0, 6])
matrix.insert(0, [8, 0, 0, 0, 4, 7, 5, 0, 3])
matrix.insert(0, [0, 5, 0, 0, 0, 3, 0, 0, 0])
matrix.insert(0, [0, 7, 0, 8, 0, 0, 0, 0, 9])
matrix.insert(0, [0, 0, 0, 0, 1, 0, 0, 0, 0])
matrix.insert(0, [9, 0, 0, 0, 0, 4, 0, 2, 0])
matrix.insert(0, [0, 0, 0, 9, 0, 0, 0, 1, 0])
matrix.insert(0, [7, 0, 8, 3, 2, 0, 0, 0, 5])
matrix.insert(0, [3, 0, 0, 0, 0, 8, 0, 0, 0])
matrix.reverse()
for sublist in matrix:
    s = str(sublist)
    print (s)
print (C)
matrix.remove("[0, 0, 0, 0, 0, 0, 0, 0, 0]")

Here is the error I keep getting:

Traceback (most recent call last):
line 17, in <module>
matrix.remove("[0, 0, 0, 0, 0, 0, 0, 0, 0]")
ValueError: list.remove(x): x not in list

I also tried using this code but Python seems to just find that it isn't in the matrix anyways. This I put in place of matrix.remove("[0, 0, 0, 0, 0, 0, 0, 0, 0]") Here it is:

if "[0, 0, 0, 0, 0, 0, 0, 0, 0]" in matrix:
    matrix.remove("[0, 0, 0, 0, 0, 0, 0, 0, 0]")

I am very new to Python and am still learning. Any help you might give me would be greatly appreciated.

Upvotes: 2

Views: 659

Answers (3)

Makoto
Makoto

Reputation: 106400

Change:

 matrix.remove("[0, 0, 0, 0, 0, 0, 0, 0, 0]")

to:

 matrix.remove([0, 0, 0, 0, 0, 0, 0, 0, 0])

The list you're looking for isn't a string; it's a list; no need to put it through as a string.

Upvotes: 0

exfizik
exfizik

Reputation: 5701

Your matrix is a list of lists of integers. What you are trying to do is to remove a string value from the list.

matrix.remove("[0, 0, 0, 0, 0, 0, 0, 0, 0]")

"[0, 0, 0, 0, 0, 0, 0, 0, 0]" is a string. Try doing

matrix.remove([0, 0, 0, 0, 0, 0, 0, 0, 0])

Note the absence of quotes around [0,...,0].

Upvotes: 1

user97370
user97370

Reputation:

In Python, a string is not the same as a list. You want

matrix.remove([0, 0, ..., 0])

and not

matrix.remove("[0, 0, ..., 0]")

But simpler would be just to construct the matrix correctly in the first place.

matrix = [
    [0, 0, 0, 5, 0, 0, 0, 0, 6],
    [8, 0, 0, 0, 4, 7, 5, 0, 3],
    [0, 5, 0, 0, 0, 3, 0, 0, 0],
    ...]

Upvotes: 4

Related Questions