Reputation: 513
I am getting this error when I run my program and I have no idea why. The error is occurring on the line that says "if 1 not in c:"
Code:
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],
[0, 7, 0, 8, 0, 0, 0, 0, 9],
[0, 0, 0, 0, 1, 0, 0, 0, 0],
[9, 0, 0, 0, 0, 4, 0, 2, 0],
[0, 0, 0, 9, 0, 0, 0, 1, 0],
[7, 0, 8, 3, 2, 0, 0, 0, 5],
[3, 0, 0, 0, 0, 8, 0, 0, 0],
]
a = 1
while a:
try:
for c, row in enumerate(matrix):
if 0 in row:
print("Found 0 on row,", c, "index", row.index(0))
if 1 not in c:
print ("t")
except ValueError:
break
What I would like to know is how I can fix this error from happening an still have the program run correctly.
Thanks in advance!
Upvotes: 8
Views: 148656
Reputation: 1033
Well, if we closely look at the error, it says that we are looking to iterate over an object which is not iterable.
Basically, what I mean is if we write 'x' in 1
, it would throw error .And if we write 'x' in [1]
it would return False
>>> 'x' in 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: argument of type 'int' is not iterable
>>> 'x' in [1]
False
So all we need to do it make the item iterable, in case of encountering this error.In this question, we can just make c
by a list [c]
to resolve the error. if 1 not in [c]:
Upvotes: 2
Reputation: 8421
Here c
is the index not the list that you are searching. Since you cannot iterate through an integer, you are getting that error.
>>> myList = ['a','b','c','d']
>>> for c,element in enumerate(myList):
... print c,element
...
0 a
1 b
2 c
3 d
You are attempting to check if 1
is in c
, which does not make sense.
Upvotes: 14
Reputation: 10351
Based on the OP's comment It should print "t" if there is a 0 in a row and there is not a 1 in the row.
change if 1 not in c
to if 1 not in row
for c, row in enumerate(matrix):
if 0 in row:
print("Found 0 on row,", c, "index", row.index(0))
if 1 not in row: #change here
print ("t")
Further clarification: The row
variable holds a single row itself, ie [0, 5, 0, 0, 0, 3, 0, 0, 0]
. The c
variable holds the index of which row it is. ie, if row
holds the 3rd row in the matrix, c = 2
. Remember that c
is zero-based, ie the first row is at index 0, second row at index 1 etc.
Upvotes: 4
Reputation: 811
You're trying to iterate over 'c' which is just an integer, holding your row number.
It should print "t" if there is a 0 in a row
Then just replace the c with the row so it says:
if 1 not in row:
Upvotes: 1
Reputation: 2120
c
is the row number, so it's an int
. So numbers can't be in
other numbers.
Upvotes: 1